JavaScript/DOM

[JavaScript]부모, 자식 노드 가져오는 방법

DevStory 2022. 11. 15.

부모, 자식 노드 가져오는 방법

이번 포스팅은 JavaScript에서 부모 노드와 자식 노드를 가져오는 방법을 소개합니다.


부모 노드 가져오는 방법

부모 노드를 가져오려면 부모 노드가 존재하는 특정 노드를 NodeList 객체로 가져와야 합니다.

 

NodeList 객체를 반환하는 메서드

- querySelectorAll()

- querySelector()

- getElementById()

- getElementByName()

 

HTMLCollection 객체를 반환하는 메서드

- getElementByTagName()

- getElementByClassName()

 

이번 포스팅은 querySelector() 메서드를 사용합니다.

 

아래는 HTML 마크업이며 id가 parent인 div 요소 하위에 세 개의 div 요소가 존재합니다.

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="parent" class="parent-class">
      <div id="child-1">child1</div>
      <div id="child-2">child2</div>
      <div id="child-3">child3</div>
    </div>

    <script src="src/index.js"></script>
  </body>
</html>

아래는 JavaScript 코드입니다. id가 child-1인 NodeList 객체를 가져온 다음 parentNode 프로퍼티를 사용하여 부모 노드를 접근합니다.

const contentSelector = document.querySelector("#child-1");

// id가 child-1인 노드
console.log(contentSelector);

// id가 child-1인 노드의 상위(부모) 노드
console.log(contentSelector.parentNode);

자식 노드 가져오는 방법

이번에는 자식 노드를 가져오는 방법을 설명합니다. 부모 노드와 마찬가지로 NodeList 객체를 반환하는 메서드를 사용해야 하며 이번에는 자식 노드가 존재하는 특정 노드를 가져옵니다.

 

모든 자식 노드를 가져오려면 childNodes 프로퍼티 또는 children 프로퍼티를 사용합니다. childNodes 프로퍼티는 태그와 태그 사이에 공백이 포함된 NodeList 객체를 반환합니다. 반면에 children 프로퍼티는 요소 노드만 존재하는 HTMLCollection 객체를 반환합니다.

const parentSelector = document.querySelector("#parent");

// id가 parent인 노드의 모든 자식 노드(NodeList)
console.log(parentSelector.childNodes);

// id가 parent인 노드의 모든 자식 노드(HTMLCollecton)
console.log(parentSelector.children);

[실행 결과]


첫 번째 자식 노드 가져오는 방법

첫 번째 자식 노드를 가져오려면 firstChild 프로퍼티 또는 firstElementChild 프로퍼티를 사용합니다.

 

NodeList는 태그와 태그 사이에 공백을 텍스트 노드로 취급하므로 firstChild 프로퍼티를 사용하면 Text 노드가 반환됩니다. 따라서 Text 노드를 제외한 첫 번째 HTML 요소를 가져오려면 firstElementChild 프로퍼티를 사용합니다.

const parentSelector = document.querySelector("#parent");

console.log(parentSelector.firstChild);
console.log(parentSelector.firstElementChild);

[실행 결과]


마지막 자식 노드 가져오는 방법

마지막 자식 노드를 가져오려면 lastChild 프로퍼티 또는 lastElementChild 프로퍼티를 사용합니다.

 

firstChild 프로퍼티와 마찬가지로 lastChild 프로퍼티는 HTML 요소, 텍스트 노드, 주석 노드를 반환합니다. 마지막 HTML 요소를 가져오려면 lastElementChild 프로퍼티를 사용합니다.

const parentSelector = document.querySelector("#parent");

console.log(parentSelector.lastChild);
console.log(parentSelector.lastElementChild);

[실행 결과]


정리

  • parentNode 프로퍼티는 현재 노드의 부모 노드를 반환합니다.
  • childNodes 프로퍼티는 자식 노드를 NodeList 객체로 반환하고 children 프로퍼티는 자식 노드를 HTMLCollection 객체로 반환합니다.
  • firstChild 프로퍼티는 첫 번째 자식 노드를 반환하며 반환 값은 HTML 요소, 텍스트 노드, 주석 노드가 될 수 있습니다.
  • firstElementChild 프로퍼티는 첫 번째 자식 노드를 HTML 요소로 반환합니다.
  • lastChild 프로퍼티는 마지막 자식 노드를 반환하며 반환 값은 HTML 요소, 텍스트 노드, 주석 노드가 될 수 있습니다.
  • lastElementChild 프로퍼티는 마지막 자식 노드를 HTML 요소로 반환합니다.
반응형

댓글