DOM(Document Object Model)은 HTML 문서를 트리 구조의 객체로 표현하는 API다. JavaScript로 DOM을 조작해 웹 페이지를 동적으로 변경할 수 있다.
DOM 트리 구조
HTML 문서:
<html>
<head><title>Page</title></head>
<body>
<h1 id="title">Hello</h1>
<p class="text">World</p>
</body>
</html>
DOM 트리:
Document
└── html
├── head
│ └── title — "Page"
└── body
├── h1#title — "Hello"
└── p.text — "World"
DOM 조작
javascript
// 요소 선택
const title = document.getElementById('title');
const texts = document.querySelectorAll('.text');
// 내용 변경
title.textContent = 'New Title';
title.innerHTML = '<em>Italic</em>';
// 스타일 변경
title.style.color = 'blue';
title.classList.add('highlight');
// 요소 생성 및 추가
const newEl = document.createElement('div');
newEl.textContent = 'New Element';
document.body.appendChild(newEl);
// 이벤트 리스너
title.addEventListener('click', () => alert('clicked!'));
이벤트 버블링
클릭 이벤트가 발생하면 자식 → 부모로 전파:
li 클릭 → ul → div → body → html
이벤트 위임 (Event Delegation):
document.getElementById('list').addEventListener('click', (e) => {
if (e.target.tagName === 'LI') {
console.log(e.target.textContent);
}
});
관련 개념
참고문헌
- •MDN Web Docs — Document Object Model