문서 객체 모델(The Document Object Model, 이하 DOM)은 HTML, XML 문서의 프로그래밍 인터페이스이다.
➡️ document
객체 사용 시 웹브라우저가 관리하고 있는 DOM 트리에 접근할 수 있다.
➡️ <html>
= document.documentElement
document
를 제외하고 DOM 트리 꼭대기에 있는 문서 노드는 <html>
태그에 해당하는 document.documentElement
이다.
➡️ <body>
= document.body
document.body
는 <body>
요소에 해당하는 DOM 노드로, 자주 쓰이는 노드 중 하나이다.
➡️ <head>
= document.head
<head>
태그는 document.head
로 접근할 수 있다.
1️⃣
childNodes
: 배열이 아닌 유사 배열 객체인 컬렉션이다.
for..of
를 사용할 수 있다.
배열이 아니기 때문에 배열 메서드는 쓸 수 없다.
배열로 사용하는 방법:
alert(Array.from(document.body.childNodes).filter);
for..in
for..in
반복문은 객체의 모든 열거 가능한 프로퍼티를 순회한다.for (let prop in document.body.childNodes) alert(prop);
parentElement
/ parentNode
parentNode
: 종류에 상관없이 부모 노드
parentElement
: 부모 '요소 노드’를 반환
같은 상황에서 다른 노드를 반환
alert(document.documentElement.parentNode); // document
alert(document.documentElement.parentElement); // null
❓ document.documentElement
의 부모는 document
인데, document
노드는 요소 노드가 아니기 때문에 parentNode
만 반환한 것이다.
위 특징을 이용해 특정 요소 탐색하기:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Traversal Example</title>
</head>
<body>
<section> <!-- 찾고 싶은 요소 -->
<div class="container">
<article>
<div>
<button class="target-element">Click Me</button>
</div>
</article>
</div>
</section>
<script>
// <section> 요소를 찾기 위한 DOM 탐색
const elem = document.querySelector(".target-element"); // 시작 요소
let currentElem = elem;
while (currentElem = currentElem.parentElement) {
if (currentElem.tagName === "SECTION") {
console.log("부모 <section> 요소를 찾았습니다:", currentElem);
break; // <section>을 찾으면 반복 종료
}
}
</script>
</body>
</html>