Computer >> 컴퓨터 >  >> 프로그램 작성 >> HTML

HTML DOM div 객체

<시간/>

HTML DOM div 개체는 HTML

요소와 연결됩니다. Div는 요소를 그룹화하여 스타일을 적용하거나 단일 태그 이름 또는 ID로 HTML 요소 그룹을 조작할 수 있는 범용 블록 수준 요소입니다.

속성

다음은 div 객체의 속성입니다 -

속성 설명
정렬
요소의 align 속성 값을 설정하거나 반환합니다. 이 속성은 HTML5에서 지원되지 않으며 정렬 대신 CSS를 사용합니다.

구문

다음은 −

의 구문입니다.

div 개체 만들기 -

var p = document.createElement("DIV");

예시

HTML DOM div 개체의 예를 살펴보겠습니다.

<!DOCTYPE html>
<html>
<body>
<h2>Div object example</h2>
<p>click on the CREATE button to create a div element with some text in it.</p>
<button onclick="createDiv()">CREATE</button>
<script>
   function createDiv() {
      var d = document.createElement("DIV");
      var txt = document.createTextNode("Sample Div element");
      d.setAttribute("style", "margin:10px;width:200px;background-color: lightgreen;border:2px solid blue");
      d.appendChild(txt);
      document.body.appendChild(d);
   }
</script>
</body>
</html>

출력

이것은 다음과 같은 출력을 생성합니다 -

HTML DOM div 객체

CREATE 버튼 클릭 시 -

HTML DOM div 객체

위의 예에서 -

사용자가 클릭할 때 createDiv() 메서드를 실행하는 CREATE 버튼을 먼저 만들었습니다. −

<button onclick="createDiv()">CREATE</button>

createDiv() 함수는

요소를 만들고 변수 d에 할당합니다. 그런 다음 텍스트 노드를 만들고 변수 txt에 할당합니다. 그런 다음 setAttribute() 메서드를 사용하여
요소 속성을 설정합니다. 그런 다음 텍스트 노드는 appendChild() 메서드를 사용하여
요소에 추가됩니다. 그런 다음 텍스트 노드와 함께
요소가 문서 본문 자식으로 추가됩니다. -

function createDiv() {
   var d = document.createElement("DIV");
   var txt = document.createTextNode("Sample Div element");
   d.setAttribute("style", "margin:10px;width:200px;background-color: lightgreen;border:2px solid blue");
   d.appendChild(txt);
   document.body.appendChild(d);
}