HTMLCollection과 NodeList는 모두 웹 브라우저에서 DOM 요소들을 묶어서 다루는 유사 배열 객체이다.
HTMLCollection
https://developer.mozilla.org/ko/docs/Web/API/HTMLCollection
HTMLCollection - Web API | MDN
HTMLCollection은 구성요소를 이름과 인덱스로 동시에 직접 노출합니다. HTML ID는 :와 .을 유효한 문자로 포함할 수 있으므로 속성 접근 시에는 괄호 표기법을 사용해야 합니다. HTMLCollection은 배열 스
developer.mozilla.org
HTML 요소 노드만 포함하며, DOM에서 실시간으로 변화가 반영되는 Live 객체다.
document.getElementById() 와 같은 메서드로 생성된다. 즉, DOM에 새로운 요소가 추가∙삭제되거나 기존 값이 변경되면 이 컬렉션에 바로 반영된다.
예제
document.body.innerHTML = `<p class="text">text</p>`;
const paragraphs = document.getElementsByTagName("p");
console.log(paragraphs[0].className); // "text"
paragraphs[0].className = "changed";
console.log(paragraphs[0].className); // "changed"
HTMLCollection은 Live 객체이기 때문에, DOM이 변경되면 자동으로 반영되는 것을 확인할 수 있다.
NodeList
https://developer.mozilla.org/en-US/docs/Web/API/NodeList
NodeList - Web APIs | MDN
Although they are both considered NodeList objects, there are 2 varieties of NodeList: live and static. In most cases, the NodeList is live, which means that changes in the DOM automatically update the collection. For example, Node.childNodes is live: cons
developer.mozilla.org
NodeList는 HTML 요소 뿐만 아니라 텍스트 노드, 주석 등 다양한 노드를 포함할 수 있다.
document.querySelectorAll() 과 같은 메서드로 생성되며, HTMLCollection과 달리 DOM 변경 후에도 변하지 않는 static한 컬렉션이다.
단, childNodes가 만든 NodeList는 예외적으로 Live 컬렉션이다.
예제
document.body.innerHTML = `<p class="text">text</p>`;
const paragraphs = document.querySelectorAll(".text");
console.log(paragraphs.length); // 1
paragraphs[0].className = "changed";
console.log(paragraphs.length); // 1
const updated = document.querySelectorAll(".text");
console.log(updated.length); // 0
paragraphs는 클래스명이 text인 정적 컬렉션이다.
paragraphs의 첫 번째 요소 클래스명을 changed로 변경했지만, NodeList는 정적이므로 변경 후 길이도 1이 된다.
다시 querySelectorAll로 조회하면 새로운 상태가 반영되어 길이가 0으로 반환된다.