DEV Community

moogoo
moogoo

Posted on

3 2

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay