JavaScript | NodeList

EHOI·2022년 8월 12일

JavaScript

목록 보기
1/2

NodeList 객체는 일반적으로 element.childNodes와 같은 속성(property)과 document.querySelectorAll 와 같은 메서드에 의해 반환되는 노드의 콜렉션입니다.

NodeListArray 는 아니지만, forEach() 를 사용하여 반복할 수 있습니다. 또한 Array.from() 을 사용하여 Array 로 변환 할 수도 있습니다.
그러나 일부 오래된 브라우저는 아직NodeList.forEach() 또는 Array.from() 를 구현하지 않았습니다.

경우에 따라, NodeList는 라이브 콜렉션으로, DOM의 변경 사항을 실시간으로 콜렉션에 반영합니다. 예를 들어, Node.childNodes 는 실시간입니다.

var parent = document.getElementById('parent');
var child_nodes = parent.childNodes;
console.log(child_nodes.length); // let's assume "2"
parent.appendChild(document.createElement('div'));
console.log(child_nodes.length); // should output "3"

다른 경우 NodeList는 정적 콜렉션입니다. DOM을 변경해도 콜렉션 내용에는 영향을 주지 않습니다. document.querySelectorAll() 은 정적 NodeList를 반환합니다.

NodeList의 항목(items)을 순회(iterate)하거나, 특히 리스트의 길이를 캐시(cache)해야 할 때, 이 구분을 유지하는것이 좋습니다.

속성과 메서드

profile
swimming in the web 🐬

0개의 댓글