#2 부모, 자식, 형제 노드
< HTMLCollection vs NodeList >
const pList1 = document.querySelectorAll('p');
const pList2 = document.getElementsbyTagName('p');
pList1;
pList2;
//출력 결과
NodeList(4) [p#first, p#second, p, p]
HTMLCollection(4) [p#first, p#second, p, p]
/*
p태그를 추가하면 NodeList(4)는 그대로 출력
HTMLCollection(5)로 변경
*/
< 부모 노드 >
const red = document.getElementsbyId('red');
red.parentNode;
red.parentElement;
document.documentElement;
document.documentElement.parentNode;
document.documentElement.parentElement;
//출력 결과
<ul id="color>...<ul>
<ul id="color>...<ul>
<html lang="ko">
<head>...</head>
<body>...</body>
</html>
#document //부모노드를 모두 반환
null //부모노드 중 요소노드만 반환(html 태그로 이루어짐)
< Node Type >
1) Node.ELEMENT.NODE - 요소 노드
2) Node.ELEMENT.NODE - 어트리뷰트 노드 (이미지 태그의 alt값)
3) Node.TEXT_NODE - 텍스트 노드
8) Node.COMMENT_NODE - 주석
< 자식 노드 >
const ul = document.getElementsbyId('color');
ul.childNodes;
ul.children;
ul.firstchild;
ul.lastchild;
ul.firstElementchild; //첫번째 요소 노드
ul.lastElementchild; //마지막 요소 노드
//출력 결과
//공백문자 포함(모든 타입)
NodeList(9) [text, li#red, text, comment, text, li#blue, text, li#green, text]
//요소만
HTMLCollection(3) [li#red, li#blue, li#green]
#text
#text
<li id="red">...</li>
<li id="green">...</li>
< 형제 노드 >
const blue = document.getElementsbyId('blue');
blue.previousSibling;
blue.nextSibling;
blue.previousElementSibling;
blue.nextElementSibling;
//출력 결과
#text
#text
<li id="red">...</li>
<li id="green">...</li>
< 정리 >
모든 노드 | 요소 노드만 | |
부모 | parentNode | parentElement |
자식 | childNodes firstChild lastChild |
children firstElementChild lastElementChild |
형제 | previousSibling nextSibling |
previousElementSibling nextElementSibling |
코딩앙마님의 유튜브 강의 "자바스크립트 DOM & EVENT"를 참고하여 작성하였습니다.
'Web > JavaScript' 카테고리의 다른 글
JavaScript 기본 #4 배열 내장 함수 (0) | 2023.09.10 |
---|---|
JavaScript 기본 #3 객체, 배열, 반복문 (0) | 2023.09.10 |
JavaScript 기본 #2 함수 (0) | 2023.09.07 |
JavaScript 기본 #1 변수, 상수, 자료형, 연산자, 조건문 (0) | 2023.09.07 |
자바스크립트 DOM & EVENT #1 노드에 접근하기 (0) | 2023.08.20 |