
DOM(Document Object Model)은 웹 브라우저가 HTML, XML 문서를 읽어들이고 이를 메모리 내에서 트리 구조의 객체 모델로 만드는 표준 모델입니다.
즉, 브라우저는 HTML 문서를 단순한 텍스트가 아니라 객체들의 집합(트리)으로 변환하여, 자바스크립트를 통해 이 객체들을 동적으로 조작할 수 있도록 합니다.
DOM은 계층적(Tree) 구조로 구성됩니다.
HTML 문서가 계층적 구조를 가지므로, 브라우저는 이를 노드(Node)들의 집합인 트리로 전환할 수 있습니다.
DOM은 여러 종류의 노드(Node)로 구성된 계층적 트리 구조입니다.
브라우저는 HTML 문서를 파싱하면서 아래와 같은 다양한 노드들을 생성합니다.
console.log(document); // Document 전체 출력
console.log(document.body); // <body> 요소 접근
console.log(document.getElementByID("main")); // 특정 요소 접근
<body>, <p>, <div>, <span> ... 등)는 모두 Element 노드입니다.<!--html-->
<p id="greeting">안녕하세요</p>
// JavaScript
const p = document.getElementById("greeting");
console.log(p.tagName); // "P"
<p>Hello</p>에서 "Hello"는 Text 노드입니다.<!--html-->
<p id="greeting">안녕하세요</p>
// JavaScript
const p = document.getElementById("greeting");
console.log(p.firstChild.nodeType); // 3 (Text 노드)
console.log(p.firstChild.nodeValue); // "안녕하세요"
| nodeType 값 | 의미 |
|---|---|
| 1 | Element 노드 (<div>, <p>, ... 등) |
| 3 | Text 노드 |
| 8 | Comment 노드 |
<!--html-->
<a id="link" href="https://example.com">Example</a>
Attribute 노드처럼 다루는 방식 (거의 안 씀)
// JavaScript
const link = document.getElementById("link");
const attrs = link.attributes;
console.log(attrs["href"].value); // "https://example.com"
일반적인 접근 방식 (가장 많이 씀)
console.log(link.href); // "https://example.com"
console.log(link.getAttribute("href")); // "https://example.com"
<!--주석입니다-->)도 DOM의 노드로 저장됩니다.<!-- html -->
<!-- 여기는 설명 주석입니다. -->
// JavaScript
const comments = document.body.childNodes;
for (let node of comments) {
if (node.nodeType === Node.COMMENT_NODE) {
console.log("주석 내용: ", node.nodeValue);
}
}
<body>
<h1></h1>
<p><span></span></p>
</body>
이 HTML은 DOM 트리에서는 다음과 같이 표현할 수 있습니다.
Document
└── html
└── body
├── h1 (id="title")
│ └── Text: "Hello World"
└── p
├── Text: "이것은 "
├── span
│ └── Text: "DOM 예제"
└── Text: " 입니다."
console.log(document); // 전체 DOM 트리 출력
console.log(document.body); // <body> 요소 접근
console.log(document.title); // 현재 문서의 제목(title) 가져오기
<p id="firstP">Sample Text</p>
위 요소(firstP)는 자바스크립트에서 다음과 같이 다룰 수 있습니다.
let firstP = document.getElementById("firstP");
console.log(firstP.tagName); // "P"
console.log(firstP.textContent); // "Sample Text"
firstP.style.color = "red"; // 글자색 변경
<!--html-->
<p id="firstP">Sample Text</p>
// JavaScript
let textNode = firstP.firstChild; // Text 노드
console.log(textNode.nodeType); // 3 (Text 노드)
console.log(textNode.nodeValue); // "Sample Text"
textNode.nodeValue = "수정된 텍스트"; // 텍스트 내용 변경
<!--html-->
<a id="link" href="https://example.com">예제</a>
// JavaScript
let link = document.getElementById("link");
// 일반적인 접근 방법 (속성처럼 다룸)
console.log(link.href); // 전체 URL 반환
console.log(link.getAttribute("href")); // "https://example.com"
// 속성 변경
link.setAttribute("title", "타이틀입니다");
참고: attributes 속성을 통해 Attribute 노드 자체에 접근할 수도 있지만, 실무에서는 거의 사용하지 않음
console.log(link.attributes["href"].value); // "https://example.com"
<!--html-->
<!-- 이것은 주석입니다 -->
// JavaScript
const nodes = document.body.childNodes;
for (let node of nodes) {
if (node.nodeType === Node.COMMENT_NODE) {
console.log("주석 내용:", node.nodeValue);
}
}
웹 브라우저는 HTML 문서를 단순한 텍스트가 아닌, 객체 구조로 변환해 웹 페이지를 화면에 표시합니다. 이 과정에서 DOM(Document Object Model)이 생성됩니다. 전체 흐름은 다음과 같습니다.
<script> 태그를 만나면 브라우저는 해당 자바스크립트를 즉시 실행합니다.DOM을 자바스크립트로 조작할 수 있다는 것은 곧, 웹 페이지의 구조나 내용을 실시간으로 동적으로 변경할 수 있다는 것을 의미합니다.
사용자와의 상호작용, 실시간 업데이트, 조건부 렌더링 등 인터랙티브한 웹 페이지를 만들기 위해 DOM 조작은 필수적입니다.
서버에서 데이터를 가져온 후, DOM을 통해 웹 페이지 내용을 변경합니다.
document.getElementById("result").textContent = "검색 결과를 가져왔습니다.";
버튼 클릭, 입력 등 사용자 이벤트에 따라 스타일이나 내용을 실시간으로 변경합니다.
document.getElementById("btn").onclick = function () {
document.body.style.backgroundColor = "lightyellow";
};
document.createElement() 등을 활용하여 새로운 요소를 추가하거나 제거할 수 있습니다.
// 새로운 리스트 항목을 동적으로 추가하는 예시
let newItem = document.createElement("li");
newItem.textContent = "동적 생성된 항목";
document.getElementById("list").appendChild(newItem);