[JS] HTMLCollection과 NodeList

조수현·2025년 7월 4일

서론

개념이 짧고 빠르게 지나가서 매 번 들어도 기억 속에 도저히 남지 않는 것 같아서 적는 글

코드로 비교

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>test</title>
  </head>
  <body>
   <main>
     <section id="section-1" data-index="1" data-name="sec1">
      <h2>섹션 1</h1>
      <p>섹션 1의 paragraph</p>
    </section>

    <section id="section-2"  data-index="2" data-name="sec2">
      <h2>섹션 2</h2>
      <p>섹션 2의 paragraph</p>
    </section>
   </main>

    <script>
        {
            const main = document.querySelector('main')
            const nodeList = main.querySelectorAll('section')
            const collection = main.children

            console.log('%c[nodeList]',"color: #ff0000;",nodeList);
            console.log('%c[collection]',"color: #0000ff;",collection );
            

        }
    </script>
  </body>
</html>


  • 각각의 데이터 형태로 main 요소의 자식을 가져옴
  • NodeList는 자식이 5개, HTMLCollection은 자식이 2개인 것을 확인
  • 아래 내용 확인 후 무엇이 다른 지 보기

HTMLCollection

  • element.children, getElementById 등 을 통해 반환된다
  • node 요소 중 element만 반환
  • 라이브 콜렉션
  • 유사 객체 배열로 배열 메서드 접근 불가 (Array.from 사용 권장)

NodeList

  • element.childNode, querySelector 등 을 통해 반환된다
  • node 요소 전체 반환 (element, text 등)
  • childNode는 라이브 콜렉션, querySelector는 정적 콜렉션
  • 유사 객체 배열인데 배열 메서드 일부 접근 가능 (Array.from 사용 권장)
NodeListHTMLCollection
업데이트정적,동적동적
배열 메서드일부 사용 가능Array.from으로 변환필요
node 종류node 전체element node만 가져옴

node vs element

nodeelement
정의DOM 트리 모든 구성 단위노드 중 HTML태그로 표현된 노드
종류태그, 주석, 텍스트, 문서오직 태그
주요 메서드textContentquerySelector, getAttribute

live collection vs static collection

<ul id="list">
  <li>item 1</li>
  <li>item 2</li>
</ul>

<button id="add">추가</button>
// HTMLCollection
const liveList = document.getElementsByTagName('li'); 
// NodeList
const staticList = document.querySelectorAll('li'); 

const button = document.getElementById('add')

button.addEventListener('click', () => {
  // li 하나 추가
  const newItem = document.createElement('li');
  newItem.textContent = 'item 3';
  document.getElementById('list').appendChild(newItem);

  console.log('HTMLCollection:', liveList.length); // 3
  console.log('NodeList:', staticList.length);     // 2
});
  • HTMLCollectionli 추가가 바로 반영이 되어 3개
  • NodeListli 추가가 반영이 안되어 2개로 남아있다
profile
프론트엔드 개발 블로그

0개의 댓글