노드 탐색
| API | 설명 |
| parentNode | 부모 노드를 반환한다. 텍스트 노드가 부모인 경우는 없다. |
| parentElement | 부모 요소 노드를 반환한다. |
| childNodes | 자식 노드를 NodeList 에 담아 반환한다. 텍스트 노드 포함 |
| children | 자식 노드를 HTMLCollection 에 담아 반환한다. 텍스트 노드 미포함 |
| firstChild | 첫 번째 노드를 반환한다. 텍스트 노드가 반환될 수 있다. |
| lastChild | 마지막 노드를 반환한다. 텍스트 노드가 반환될 수 있다. |
| firstElementChild | 첫 번째 자식 요소 노드를 반환한다. 텍스트 노드 미포함 |
| lastElementChild | 마지막 자식 요소 노드를 반환한다. 텍스트 노드 미포함 |
| previousSibling | 자신의 이전 형제 노드를 반환한다. 텍스트 노드가 반환될 수 있다. |
| nextSibling | 자신의 다음 형제 노드를 반환한다. 텍스트 노드가 반환될 수 있다. |
| previousElementSibling | 자신의 이전 요소 노드를 반환한다. 텍스트 노드 미포함 |
| nextElementSibling | 자신의 다음 요소 노드를 반환한다. 텍스트 노드 미포함 |
parent
- 부모가 텍스트 노드 형태인 경우는 없다. 따라서 두 속성 모두 같은 동작을 한다.
<body>
<ul class="parent">
<li class="child">a</li>
<li class="child">b</li>
<li class="child">c</li>
</ul>
<script>
const $child = document.querySelector(".child");
console.log($child.parentNode); // <ul class="parent"> ... </ul>
console.log($child.parentElement); // <ul class="parent"> ... </ul>
</script>
</body>
child
- hasChildNodes 메소드를 사용해 자식노드가 존재하는지 확인할 수 있다.
- 텍스트 노드도 존재하면 true 를 리턴한다.
<body>
<ul class="parent">
<li class="child">a</li>
<li class="child">b</li>
<li class="child">c</li>
</ul>
<script>
const $parent = document.querySelector(".parent");
console.log($parent.hasChildNodes()); // true
console.log($parent.childNodes); // NodeList(7) [text, li.child, text ... li.child, text]
console.log($parent.children); // HTMLCollection(3) [li.child, li.child, li.child]
console.log($parent.firstChild); // #text
console.log($parent.firstElementChild); // <li class="child">a</li>
</script>
</body>
sibling
<body>
<ul class="parent">
<li class="child">a</li>
<li class="child middle">b</li>
<li class="child">c</li>
</ul>
<script>
const $child = document.querySelector(".child.middle");
console.log($child.previousSibling); // #text
console.log($child.previousElementSibling); // <li class="child">a</li>
</script>
</body>
Reference
- 모던 자바스크립트 - 이웅모
There might be incorrect information or outdated content.
'Web > Javascript' 카테고리의 다른 글
| [JAVASCRIPT] isNaN 검사 (0) | 2023.08.15 |
|---|---|
| [JAVASCRIPT] DOM - 노드 조작 (0) | 2023.08.04 |
| [JAVASCRIPT] DOM - 노드 취득 (HTMLCollection) (0) | 2023.08.04 |
| [JAVASCRIPT] Full Screen (0) | 2023.07.29 |
| [JAVASCRIPT] STRING (0) | 2023.07.29 |