브라우저의 렌더링 엔진은 웹 문서를 로드한 후 파싱하여 브라우저가 이해할 수 있는 구조로 구성하고 메모리에 적재하는데, 이를 DOM
이라고 한다.
모든 요소와 요소의 속성, 텍스트를 각각의 객체로 만들고 트리 구조
를 구성한다.
자바스크립트를 통해 모든 객체에 접근할 수 있고, 동적으로 변경할 수 있다.
DOM에서 모든 요소, 속성, 텍스트는 하나의 객체이며 Document 객체의 자식이다.
DOM Tree의 진입점은 document
이며, 최종점은 요소의 텍스트
를 나타내는 객체이다.
크롬 브라우저 개발자 도구의 Element - Properties에서 DOM Tree를 확인할 수 있다.
<!DOCTYPE html>
<html>
<head>
<style>
.red { color: #ff0000; }
.blue { color: #0000ff; }
</style>
</head>
<body>
<div>
<h1>Cities</h1>
<ul>
<li id="one" class="red">Seoul</li>
<li id="two" class="red">London</li>
<li id="three" class="red">Newyork</li>
<li id="four">Tokyo</li>
</ul>
</div>
</body>
</html>
텍스트 노드의 생성에는 두가지 예외가 있다.
<head>
이전의 공백과 새 줄은 무시된다.</body>
뒤에 공백이 존재할 수 없다. 뒤에 있는 콘텐츠는 자동으로 안쪽으로 옮겨진다.기형적인 HTML을 만나면 브라우저는 DOM 생성 과정에서 HTML을 자동으로 교정한다.
<html>
, <body>
, <head>
태그가 없는 경우 자동으로 추가한다.노드 타입은 총 열두 가지인데, 주로 네 가지 노드를 다룬다.
문서 노드 (Document Node)
요소 노드 (Element Node)
어트리뷰트 노드 (Attribute Node)
텍스트 노드 (Text Node)
DOM 요소에 접근하기 위해 사용할 수 있는 document 객체의 메서드가 있다.
document.getElementById
document.querySelector
document.getElementsByClassName
querySelectorAll
메소드를 사용하는 방법이 있다.document.getElementsByTagName
document.querySelectorAll
특정 DOM 요소에서 탐색을 통해 다른 DOM 요소에 접근할 수 있다.
parentNode
firstChild
, lastChild
firstElementChild
, lastElementChild
를 사용한다.hasChildNodes
childNodes
children
previousSibling
, nextSibling
previousElementSibling
, nextElementSibling
Reference
https://poiemaweb.com/js-dom
https://ko.javascript.info/dom-nodes