02. 노드 탐색 방법

양희준·2022년 2월 13일
0

DOM

목록 보기
2/8
post-thumbnail

📌 2-1 노드의 탐색 방향

선택 노드 기준으로 다른 노드들을 탐색을 원할 때 사용한다.

💡 보통 부모 노드 기준으로 자식 노드를 탐색 하는 방법을 주로 사용한다.
💡 검색 방법은 자식 노드 검색, 부모 노드 검색, 형제 노드 검색이 있다.

📌 2-2 자식 노드 탐색

🧩 Node.prototype.childNodes
🧩 Element.prototype.children

✔ Node의 프로퍼티를 사용하면 텍스트 노드도 포함하여 반환할 수 있다.
✔ Element의 프로퍼티를 사용하면 요소 노드만 포함해서 반환한다.

<!DOCTYPE html>
<html lang="kr">
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <ul id="animals">
            <li id="dog">Dog</li>
            <li id="cat">Cat</li>
        </ul>
    </body>
    <script>
        const $animals = document.querySelector("#animals");
        // node는 텍스트 노드도 포함되기 때문에 텍스트 노드도 포함되어 있다.
        const $nodeList = $animals.childNodes;
        // Element 프로퍼티라서 요소 노드만 포함된다.
        const $HTMLCollection = $animals.children;
        // 결과 : NodeList(5) [text, li#dog, text, li#cat, ...]
        console.log($nodeList);
        // 결과 : HTMLCollection(2) [li#dog, li#cat, ...]
        console.log($HTMLCollection);
    </script>
</html>

📌 2-3 부모 노드 탐색

🧩 Node.protype.parentNode

✔ 바로 위의 부모 노드를 반환한다.

<!DOCTYPE html>
<html lang="kr">
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <ul id="animals">
            <li id="dog">Dog</li>
            <li id="cat">Cat</li>
        </ul>
    </body>
    <script>
        const $dog = document.querySelector("#dog");
        const $parent = $dog.parentNode;
        // 결과 : <ul id="animals">...</ul>
        console.log($parent);
    </script>
</html>

📌 2-4 형제 노드 탐색

🧩 Element.prototype.previousElementSibling
🧩 Element.prototype.nextiousElementSibling

✔ previousElementSibling은 선택 노드 기준으로 왼쪽에 있는 노드이다.
✔ nextiousElementSibling은 선택 노드 기준으로 오른쪽에 있는 노드이다.

<!DOCTYPE html>
<html lang="kr">
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <ul id="animals">
            <li id="pig">Pig</li>
            <li id="dog">Dog</li>
            <li id="cat">Cat</li>
        </ul>
    </body>
    <script>
        const $dog = document.querySelector("#dog");
        const $Sibling1 = $dog.previousElementSibling;
        const $Sibling2 = $dog.nextElementSibling;
        // 결과 : <li id="pig>...</li>
        console.log($Sibling1);
        // 결과 : <li id="cat>...</li>
        console.log($Sibling2);
    </script>
</html>
profile
JS 코린이

0개의 댓글