jennet1 님의 블로그

JS [children childrenNodes] 본문

WEB/JS

JS [children childrenNodes]

jennet1 2024. 9. 22. 19:44

children ? childrenNodes ?

- DOM 에서 부모 요소의 자식 요소를 가져올 때 사용한다. 둘다 반환하는 값이나 활용하는 상황이 다르니 차이점을 이해해 보자

1. children 

  • 부모 요소의 자식 요소들 중 HTML 요소만 반환한다.
  • 태그 요소들만 가져옴 , 텍스트나 노드 주석은 다 무시한다.
  • 반환 값은 HTMLCollection 입니다. foreach 문을 사용할 수 없지만 for(basic) 가능하다.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

  <div id="parent">
    Text 
    <div id="two">div 두번째 Text</div>
    <div>div 세번째 Text</div>
  </div>

    <script>
     const parent = document.querySelector("div");
     const parentChild = parent.children;
 
     for(let i = 0; i < parentChild.length; i++) {
      console.log(parentChild[i]);
     }
  
    </script>
</body>
</html>

2. childNodes

  • 부모 요소의 모든 자식 노드를 가져온다.
  • HTML 요소뿐만 아니라 노드,공백,주석 등 모든 노드를 반환한다.
  • NodeList 배열이 아니지만, 대부분 forEach 문 사용이 가능
<body>

  <div id="parent">
    Text 
    <div id="two">div 두번째 Text</div>
    <div>div 세번째 Text</div>
  </div>

    <script>
     const parent = document.querySelector("div");
     const Nodes = parent.childNodes;
 
     for(let i = 0; i < Nodes.length; i++) {
      console.log(Nodes[i]);
     }
  
    </script>
</body>
</html>

 

 

3. HTMLCollection 자식노드에 접근해보기

namedItem 을 사용하여 자식 노드에 접근이 가능하다

<body>
  <div id="parent">
    Text 
    <div id="two">div 두번째 Text</div>
    <div>div 세번째 Text</div>
  </div>

    <script>
     const parent = document.getElementById("parent");
     const child = parent.children;
     const Nodes = parent.childNodes;
    
     console.log(child.namedItem("two"));
    </script>
</body>
</html>

4. 활용예시

  • children  : HTML 자식요소들의 태그를 선택하여 특정한 스타일을 변경하고 싶을 때 유용하다.
  • childNodes : 모든 노드에 접근 할 필요가 있을때 사용한다.
<body>

  <div id="parent">
    <ul>
 
      <li>
        <h3>첫번째 텍스트</h3>
        <span>li1</span>
      </li>
      <li>
        <h3>첫번째 텍스트</h3>
        <span>li1</span>
      </li>
      <li>
        <h3>첫번째 텍스트</h3>
        <span>li1</span>
      </li>
      <li>
        <h3>첫번째 텍스트</h3>
        <span>li1</span>
      </li>
    </ul>
  </div>

    <script>
     const parent = document.querySelector("div");
     const child = parent.children;
     const Nodes = parent.childNodes;
     
     console.log(child);
     console.log(Nodes);
    </script>

 

'WEB > JS' 카테고리의 다른 글

JS [이벤트 발생]  (1) 2024.09.23
JS [random]  (0) 2024.09.23
JS [DOM TEXT]  (0) 2024.09.21
JS [DOM]  (0) 2024.09.21
JS [함수]  (0) 2024.09.20