DEV Community

moogoo
moogoo

Posted on

JavaScript: Live vs. Static NodeLists

There are two types of NodeList: live and static

live NodeList means that changes in the DOM automatically update the collection.

  • Node.childNodes is a live NodeList
  • document.querySelectorAll() returns static NodeList Node

Sample Code:

HTML

<div id="parent">
  <div class="child">1</div>
  <div class="child">2</div>
  <div class="child">3</div>
</div>
Enter fullscreen mode Exit fullscreen mode

JavaScript

const liveParent = document.querySelector('#parent');
const staticChildren = document.querySelectorAll('.child');
console.log(liveParent.childNodes, staticChildren);
liveParent.appendChild(document.createElement('div'));
console.log(liveParent.childNodes, staticChildren);
Enter fullscreen mode Exit fullscreen mode

Results:

javascript-live-static-node-list-sample

You can see that the length of staticChildren still the same after the parent object append a child.

Top comments (0)