Space
article thumbnail
Published 2023. 6. 7. 18:09
[JS] DOM (1) JavaScript
반응형

DOM (문서 객체 모델) 이란?

(Document Object Model)

 

 

DOM 구조

 

 

자바스크립트의 DOM은 트리구조를 띄고 있습니다.

 

// 트리 자료구조 (tree data structure)
트리 자료구조는 노드들의 계층 구조로 이루어진다. 
즉, 트리 자료구조는 부모 노드와 자식 노드로 구성되어 
노드 간의 계층적 구조(부자, 형제 관계)를 표현하는 비선형 자료구조를 말한다.

트리 자료구조는 하나의 최상위 노드에서 시작한다.

// 루트 노드 (root node)
최상위 노드를 말하고, 최상위 노드는 부모 노드가 없다.
루트 노드는 0개 이상의 자식 노드를 갖는다.

// 리프 노드 (leaf node)
자식 노드가 없는 노드를 말한다.

 

HTML 요소를 JavaScript의 Object처럼 조작할 수 있는 Model입니다.
= JavaScript의 DOM으로 HTML를 조작할 수 있습니다.
 

반응형

자식 노드 탐색

// Node.prototype.childNodes
자식 노드를 모두 탐색하여 DOM 컬렉션 객체인 NodeList에 담아 반환한다.
childNodes 프로퍼티가 반환한 NodeList에는 요소 노드뿐만 아니라
텍스트 노드도 포함되어 있을 수 있다.

// Element.prototype.children
자식 노드 중에서 요소 노드만 모두 탐색하여 DOM 컬렉션 객체인 HTMLCollection에 담아 반환한다.
children 프로퍼티가 반환한 HTMLCollection에는 텍스트 노드가 포함되지 않는다.

// Node.prototype.firstChild
첫 번째 자식 노드를 반환한다.
firstChild 프로퍼티가 반환한 노드는 텍스트 노드이거나 요소 노드이다.

// Node.prototype.lastChild
마지막 자식 노드를 반환한다.
lastChild 프로퍼티가 반환한 노드는 텍스트 노드이거나 요소 노드이다.

// Element.prototype.firstElementChild
첫 번째 자식 요소 노드를 반환한다.
firstElementChild 프로퍼티는 요소 노드만 반환한다.

// Element.prototype.lastElementChild
마지막 자식 요소 노드를 반환한다.
lastElementChild 프로퍼티는 요소 노드만 반환한다.
<!-- example -->

<!DOCTYPE html>
<html lang="en">
<body>
    <ul id="fruits">
        <li class="apple">Apple</li>
        <li class="banana">Banana</li>
        <li class="orange">Orange</li>
    </ul>    
</body>
<script>
    // 노드 탐색의 기점이 되는 #fruits 요소 노드를 취득한다.
    const $fruits = document.querySelector('#fruits');

    // #fruits 요소의 모든 자식 노드를 탐색한다.
    // childNodes 프로퍼티가 반환한 NodeList에는 요소 노드뿐만 아니라 텍스트 토드도 포함되어 있다.
    console.log($fruits.childNodes);
    // NodeList(7) [text, li.apple, text, li.banana, text, li.orange, text]

    // #fruits 요소의 모든 자식 노드를 탐색한다.
    // children 프로퍼티가 반환한 HTMLCollection에는 요소 노드만 포함되어 있다.
    console.log($fruits.children);
    // HTMLCollection(3) [li.apple, li.banana, li.orange]

    // #fruits 요소의 첫 번째 자식 노드를 탐색한다.
    // firstChild 프로퍼티는 텍스트 노드를 반환할 수도 있다.
    console.log($fruits.firstChild);  // text

    // #fruits 요소의 마지막 자식 노드를 탐색한다.
    // lastChild 프로퍼티는 텍스트 노드를 반환할 수도 있다.
    console.log($fruits.lastChild);  // text

    // #fruits 요소의 첫 번째 자식 노드를 탐색한다.
    // firstElementChild 프로퍼티는 요소 노드만 반환한다.
    console.log($fruits.firstElementChild);  // li.apple

    // #fruits 요소의 마지막 자식 노드를 탐색한다.
    // lastElementChild 프로퍼티는 요소 노드만 반환한다.
    console.log($fruits.lastElementChild);  // li.orange
</script>
</html>

 


자식 노드 확인

<!-- Node.prototype.hasChildNodes -->
텍스트 노드를 포함하여 자식이 존재하면 true, 존재하지 않으면 false를 반환한다.

<!DOCTYPE html>
<html lang="en">
<body>
    <ul id="fruits">
    </ul>
</body>
<script>
    // 노드 탐색의 기점이 되는 #fruits 요소 노드를 취득한다.
    const $fruits = document.querySelector('#fruits');

    // #fruits 요소에 자식 노드가 존재하는지 확인한다.
    // hasChildNodes 메서드는 텍스트 노드를 포함하여 자식 노드의 존재를 확인한다.
    console.log($fruits.hasChildNodes());  // true
</script>
</html>

부모 노드 탐색

<!-- Node.prototype.parentNode -->

<!DOCTYPE html>
<html lang="en">
<body>
    <ul id="fruits">
        <li class="apple">Apple</li>
        <li class="banana">Banana</li>
        <li class="orange">Orange</li>
    </ul>    
</body>
<script>
    // 노드 탐색의 기점이 되는 #fruits 요소 노드를 취득한다.
    const $fruits = document.querySelector('.banana');

    // .banana 요소 노드의 부모 노드를 탐색한다.
    console.log($banana.parentNode);  // ul#fruits
</script>
</html>

형제 노드 탐색

// Node.prototype.previousSibling
부모 노드가 같은 형제 노드 중에서 자신의 이전 형제 노드를 탐색하여 반환한다.
proviousSibling 프로퍼티가 반환하는 형제 노드는 요소 노드뿐만 아니라 텍스트 노드일 수도 있다.

// Node.prototype.nextSibling
부모 노드가 같은 형제 노드 중에서 자신의 다음 형제 노드를 탐색하여 반환한다.
nextSibling 프로퍼티가 반환하는 형제 노드는 요소 노드뿐만 아니라 텍스트 노드일 수도 있다.

// Element.prototype.previousElementSibling
부모 노드가 같은 형제 요소 노드 중에서 자신의 이전 형제 요소 노드를 탐색하여 반환한다.
previousElementSibling 프로퍼티는 요소 노드만 반환한다.

// Element.prototype.nextElementSibling
부모 노드가 같은 형제 요소 노드 중에서 자신의 다음 형제 요소 노드를 탐색하여 반환한다.
nextElementSibling 프로퍼티는 요소 노드만 반환한다.
<!-- example -->

<!DOCTYPE html>
<html lang="en">
<body>
    <ul id="fruits">
        <li class="apple">Apple</li>
        <li class="banana">Banana</li>
        <li class="orange">Orange</li>
    </ul>    
</body>
<script>
    // 노드 탐색의 기점이 되는 #fruits 요소 노드를 취득한다.
    const $fruits = document.querySelector('#fruits');

    // #fruits 요소의 첫 번째 자식 노드를 탐색한다.
    // firstChild 프로퍼티는 요소 노드뿐만 아니라 텍스트 노드를 반환할 수도 있다.
    const { firstChild } = $fruits;
    console.log(firstChild);  // #text

    // #fruits 요소의 첫 번째 자식 노드(텍스트 노드)의 다음 형제 노드를 탐색한다.
    // nextSibling 프로퍼티는 요소 노드뿐만 아니라 텍스트 노드를 반환할 수도 있다.
    const { nextSibling } = firstChild;
    console.log(nextSibling);  // li.apple

    // li.apple 요소의 이전 형제 노드를 탐색한다.
    // previousSibling 프로퍼티는 요소 노드뿐만 아니라 텍스트 노드를 반환할 수도 있다.
    const { previousSibling } = nextSibling;
    console.log(previousSibling);  // #text
    
    // #fruits 요소의 첫 번째 자식 노드를 탐색한다.
    // firstElementChild 프로퍼티는 요소 노드만 반환한다.
    const { firstElementChild } = $fruits;
    console.log(firstElementChild);  // li.apple
    
    // #fruits 요소의 첫 번째 자식 노드(li.apple)의 다음 형제 노드를 탐색한다.
    // nextElementSibling 프로퍼티는 요소 노드만 반환한다.
    const { nextElementSibling } = firstElementChild;
    console.log(nextElementSibling);  // li.banana
    
    // li.banana 요소의 이전 형제 요소 노드를 탐색한다.
    // previousElementSibling 프로퍼티는 요소 노드만 반환한다.
    const { previousElementSibling } = nextElementSibling;
    console.log(previousElementSibling);  // li.apple
    </script>
</html>

노드 정보 취득

// Node.prototype.nodeType
노드 객체의 종류, 즉 노드 타입을 나타내는 상수를 반환한다.
  - Node.ELEMENT_NODE : 요소 노드 타입을 나타내는 상수 1을 반환
  - Node.TEXT_NODE    : 텍스트 노드 타입을 나타내는 상수 3을 반환
  - Node.DOCUMENT_NODE: 문서 노드 타입을 나타내는 상수 9을 반환

// Node.prototype.nodeName
노드의 이름을 문자열로 반환한다.
  - 요소 노드   : 대문자 문자열로 태그 이름("UL", "LI" 등)을 반환
  - 텍스트 노드 : 문자열 "#text"를 반환
  - 문서 노드   : 문자열 "#document"를 반환
<!DOCTYPE html>
<html lang="en">
<body>
    <div id="foo">Hello</div>
</body>
<script>
    // 문서 노드의 노드 정보를 취득한다.
    console.log(documnet.nodeType);  // 9
    console.log(documnet.nodeName);  // #document
    
    // 요소 노드의 노드 정보를 취득한다.
    const $foo = document.querySelector('#foo');
    console.log($foo.nodeType);  // 1
    console.log($foo.nodeName);  // DIV
    
    // 텍스트 노드의 노드 정보를 취득한다.
    const $textNode = $foo.firstChild;
    console.log($textNode.nodeType);  // 3
    console.log($textNode.nodeName);  // #text
</script>
</html>

 

 

DOM (1)을 알아보는 시간이었습니다.
틀린 내용은 댓글로 알려주시면 감사하겠습니다.

 
 

반응형
profile

Space

@Space_zero

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!