[JS]자식 노드 탐색

Sunset·2022년 12월 16일
0

Javascript/Jquery

목록 보기
6/7

자식 노드를 탐색하기 위한 프로퍼티 정리

프로퍼티설명
Node.prototype.
childNodes
자식 노드를 모두 탐색하여 DOM 컬렉션 객체인 NodeList에 담아 반환한다.
childNodes 프로퍼티가 반환한 NodeList에는 요소노드뿐만 아니라 텍스트 노드도 포함되어 있을 수 있다.
Element.prototype.
children
자식 노트 중에서 요소 노드만 모두 탐색하여 DOM 컬렉션 객체인 HTMLCollection에 담아 반환한다.
child 프로퍼티가 반환한 HTMLCollection에는 텍스트 노드가 포함되지 않는다.
Node.prototype.
firstChild
첫번째 자식 노드를 반환한다.
firstChild 프로퍼티가 반환한 노드는 텍스트 노드이거나 요소 노드이다.
Node.prototype.
lastChild
마지막 자식 노드를 반환한다.
lastChild 프로퍼티가 바환한 노드는 텍스트 노드이거나 요소 노드이다.
Element.prototype.
firstElementChild
첫번째 자식 요소 노드를 반환한다.
firstElementChild 프로퍼티는 요소 노드만 반환한다.
Element.prototype.
lastElementChild
마지막 자식 요소 노드를 반환한다.
lastElementChild 프로퍼티는 요소 노드만 반환한다




<!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>
    const $fruits = document.getElementById('fruits');

    console.log($fruits.childNodes);
    // NodeList(7) [text, li.apple, text, li.banana, text, li.orange, text]

    console.log($fruits.children);
    // HTMLCollection(3) [li.apple, li.banana, li.orange]

    console.log($fruits.firstChild);
    // #text

    console.log($fruits.lastChild);
    // #text

    console.log($fruits.firstElementChild);
    // li.apple

    console.log($fruits.lastElementChild);
    // li.orange
</script>
</html>

Node 프로퍼티는 텍스트노드(공란)이 반환 될수 있다!

<ul id="fruits">""
	<li class="apple">Apple</li>""
	<li class="banana">Banana</li>""
	<li class="orange">Orange</li>""
</ul>
<!-- 총 7 개 노드 -->

0개의 댓글