[JavaScript] 부모, 자식, 형제 노드 접근하기 ✅

parkheeddong·2023년 5월 2일

JavaScript

목록 보기
16/26
post-thumbnail

✨ 부모노드

parentNode, parentElement로 접근한다.

parentNode ➡ 부모 노드 중 모든 노드를 반환한다.
parentElement ➡ 부모 노드 중에 요소 노드를 반환한다.

    <ul id = 'color' >
        <li id = 'red'>  red </li>
        <li id = 'blue'> blue </li>
        <li id = 'yellow'>  yellow </li>
    </ul>
const yellow = document.getElementById('yellow');
yellow.parentNode; // <ul id = 'color'> .. </ul>
yellow.parentElement; // <ul id = 'color'> .. </ul>

👀 Example : html의 부모는 ..?

document.documentElement.parentNode; // #document
document.documentElement.parentElement; //null
➡ html 태그의 부모노드는 document이다.
➡ document 노드는 요소노드가 아니므로, 두번째는 null이다.




✨ 자식노드

childNodes, children을 접근한다.

childNodes ➡ 모든 자식 노드를 반환한다.
children ➡ 자식 노드 중 요소노드만 반환한다.

const ul = document.getElementById('color');
ul.childNodes; 
// NodeList(7) [text, li#red, text, li#blue, text, li#yellow, text]
ul.children; 
// HTMLCollection(3) [li#red, li#blue, li#yellow, red: li#red, blue: li#blue, yellow: li#yellow]

firstChild, firstElementChild / lastChild, lastElementChild로 접근한다.

firstChild, lastChild ➡ 첫, 마지막 자식 노드이다.
firstElementChild, lastElementChild ➡ 첫, 마지막 자식 '요소'노드이다.

ul.firstChild;  // #text
ul.lastChild;   // #text
ul.firstElementChild; // <li id="red"></li>
ul.lastElementChild; // <li id="yellow"></li>

👇 NodeList와 HTMLCollection의 차이

NodeList는 모든 타입의 노드들이다.
HTMLCollection은 html 요소 타입의 노드들이다.
HTMLCollection은 노드 변경사항이 실시간 반영되지만, NodeList는 아니다.
예외로 childNodes는 노드의 변경사항이 NodeList도 HTMLCollection처럼 실시간 반영으로 동작한다.




✨ 형제노드

previousSibling , nextSibling, previousElementSibling, nextElementSibling으로 접근한다.
previousSibling , nextSibling ➡ 형제 노드중 모든 타입을 가져온다
previousElementSibling , nextElementSibling ➡ 형제 노드 중 요소 타입의 노드를 반환한다.

const blue = document.getElementById('blue');
blue.previousSibling  // #text
blue.nextSibling    // #text
blue.previousElementSibling  // <li id="red">  red </li>
blue.nextElementSibling      // <li id="yellow">  yellow </li>


0개의 댓글