프로그래밍 공부/Javascript

HTMLCollection 과 NodeList

Kevinkb 2021. 10. 3. 17:03

HTMLCollection과 NodeList는 DOM을 사용하다 보면 볼 수 있는 컬렉션이다. 둘 다 배열처럼 보이지만 배열이 아닌 유사배열이고 각각 특징이 다르기 때문에 자세하게 살펴본다.

<body>
    <label>아이디</label>
    <input type="text" id="username">텍스트노드
    <div class="failure-message hide">4~20자의 영문 소문자, 숫자만 사용 가능합니다.</div>
    <div class="includes-message hide">이미 사용하고 있는 아이디입니다.</div>
</body>

HTMLCollection

HTMLCollection은 문서 내에 순서대로 정렬된 요소(Element)의 컬렉션이며 유사배열이다. children 프로퍼티를 이용해 접근할 수 있다.

const collection = document.body.children

console.log(collection);
// HTMLCollection(4) [label, input#username, div.failure-message.hide, div.includes-message.hide]

NodeList

element.childNodes와 같은 프로퍼티와 document.querySelectAll 와 같은 메서드로 반환되는 노드(Node)의 컬렉션이며 유사배열이다. 하지만 NodeList는 forEach, entries, keys, values 메서드를 사용하여 반복할 수 있다(브라우저간 차이가 있을 수 있다).

const nodeList = document.body.childNodes;

console.log(nodeList); 
//NodeList(9) [text, label, text, input#username, text, div.failure-message.hide, text, div.includes-message.hide, text]
console.log(nodeList[4].data);  // "텍스트노드\n      "

※childNodes와 querySelectorAll의 차이

  • Node.childNodes가 반환한 NodeList는 라이브 컬렉션으로, DOM의 변경사항을 실시간 반영
  • document.querySelectorAll가 반환한 NodeList는 정적 컬렉션으로, DOM이 변경되도 collection의 내용에 반영되지 않는다.

유사배열을 배열로 바꾸는 방법

전개 구문, Array.from 메서드, Array.prototype.slice.call 메서드를 사용한다.

const collection = document.body.children;
const nodeList = document.body.childNodes;

// 전개 구문
[...collection]  // Array
[...nodeList]    // Array

// Array.from
Array.from(collection)   // Array
Array.from(nodeList)     // Array

// Array.prototype.slice.call
const array_collection = Array.prototype.slice.call(collection);  // Array
const array_nodeList = Array.prototype.slice.call(nodeList);      // Array