NodeList

Bruce·2021년 6월 22일
0

프론트엔드 코어

목록 보기
28/31

노드리스트(NodeList)란 무엇인가?

MDN에는 이렇게 기술되어 있다.

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

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

경우에 따라, 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
Figure it out yourself

0개의 댓글