Updating the DOM is very common in web development practices in 2020. Knowing how to use your selectors is even more so.
- Brief overview on
querySelectorAlland its not "live" (static) properties.
.getElementsByClassNameand its "live" properties. (and whatever that means...).
The difference between .querySelectorAll and .getElementsByClassName
This returns a NodeList of non-live nodes using a valid css selector. More about selectors.
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>
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
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
Here's a codepen for you to play with and see for yourself!
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
querySelectorAll, don't fret, just simply re-query the DOM to get the latest changes!
Thanks for reading!
Top comments (0)