[JS]형제 노드 탐색

Sunset·2022년 12월 17일
0

Javascript/Jquery

목록 보기
7/7
프로퍼티설명
Node.protytype.
previousSibling
부모 노드가 같은 형제 노드 중에서 자신의 이전 현제 노드를 탐색하여 반환한다.
previousSibling 프로퍼티가 반환하는 형제 노드는 요소 노드 뿐만아니라 텍스트 노드일 수도 있다.
Node.protytype.
nextSibling
부모 노드가 같은 형제 노드 중에서 자신의 다음 형제 노드를 탐색하여 반환한다.
nextSibling 프로퍼티가 반환하는 형제 노드는 요소 노드 뿐만 아니라 텍스트 노드일 수도 있다.
Element.protytype.
previousElementSibling
부모 노드가 같은 형제 요소 노드 중에서 자신의 이전 형제 요소 노드를 탐색하여 반환한다.
previousElementSibling 프로퍼티는 요소 노드만 반환한다.
Element.protytype.
nextElementSibling
부모 노드가 같은 형제 노드 중에서 자신의 다음 형제 요소 노드를 탐색하여 반환한다.
nextElementSibling 프로퍼티는 요소 노드만 반환한다.




<!DOCTYPE html>
<html>
<body>
    <ul id="fruits">
        <li class="apple">Apple</li>
        <li class="banana">Banana</li>
        <li class="orange">Orange</li>
    </ul>
</body>
<script>
    // 노드 탐색의 기점이 되는 id="fruits"를 가져온다.
    const $fruits = document.getElementById('fruits');

    // #fruits의 첫번째 요소 ""(공백)
    const {firstChild} = $fruits;
    console.log(firstChild); // #text

    // 위 공백,텍스트노드의 다음 형제 노드
    const {nextSibling} = firstChild;
    console.log(nextSibling); // li.apple

    // 위 li.apple 이전의 노드
    const {previousSibling} = nextSibling;
    console.log(previousSibling); // #text

    // #fruits 요소의 첫번째 노드
    const {firstElementChild} = $fruits;
    console.log(firstElementChild); // li.apple

    // 위 첫번째 요소의 다음 노드
    const {nextElementSibling} = firstElementChild;
    console.log(nextElementSibling); // li.banana

    // 위 li.apple의 이전 노드
    const {previousElementSibling} = nextElementSibling;
    console.log(previousElementSibling); // li.apple
</script>
</html>

0개의 댓글