DEV Community

Scott
Scott

Posted on

Live vs static node lists when querying the DOM.

Updating the DOM is very common in web development practices in 2020. Knowing how to use your selectors is even more so.

TLDR;

  • Brief overview on .querySelectorAll and .getElementsByClassName.
  • querySelectorAll and its not "live" (static) properties.
  • .getElementsByClassName and its "live" properties. (and whatever that means...).

The difference between .querySelectorAll and .getElementsByClassName

querySelectorAll

This returns a NodeList of non-live nodes using a valid css selector. More about selectors.

getElementsByClassName

Returns a live NodeList using css class names as your selector.

What are "live" collections?

Now...we got through the paperwork, we can have some fun.

Live node lists update as the DOM updates, non-live or static node lists do not. For example, if I query the DOM for the same collection, one using .querySelectorAll and the other using .getElementsByClassName. After I make an update to the DOM, only one node list will reflect the changes and the other will have stale data.

Can you guess which one it is?

DING DING DING! It is in fact .getElementsByClassName!!!!!

<ul>
  <li class="list-item">One</li>
  <li class="list-item">Two</li>
  <li id="three">Three</li>
</ul>
Enter fullscreen mode Exit fullscreen mode
const liveElements = document.getElementsByClassName('list-item');

const notLiveElements = document.querySelectorAll('.list-item');

console.log(liveElements.length); // length of 2
console.log(notLiveElements.length); // length of 2 

document.getElementById('three').className = 'list-item';

console.log(liveElements.length); // length of 3
console.log(notLiveElements.length); // length of 2
Enter fullscreen mode Exit fullscreen mode

NOTICE, when we added a className to the node with an id of three, the changes were reflected in the node list that we got using .getElementsByClassName, but were NOT reflected using .querySelectorAll

Here's a codepen for you to play with and see for yourself!

Parting notes

When using DOM selectors like the one above, please be aware if the node list is live or static. For the sake of this article I'm not recommending using one over the other. What I am advocating for is knowing the consequences of the tools you are using.

If you are in fact using querySelector or querySelectorAll, don't fret, just simply re-query the DOM to get the latest changes!

Thanks for reading!

Scott

Resources

Top comments (0)