JS Tip of the Day: Live DOM Lists

Live DOM Lists
Level: Intermediate

When grabbing collections of elements from the DOM, you may find yourself with what is considered a “live” collection. These lists of elements will change and update as the DOM updates. If you have a variable that starts with a certain number of elements and the DOM updates adding more elements to (and/or removing some from) the DOM tree, your variable - if live - will automatically update to reflect the changes in the DOM.

<div id="container">
    <span></span>
    <span></span>
    <span></span>
</div>

<script>
let container = document.getElementById('container');
let liveSpans = container.getElementsByTagName('span');
console.log(liveSpans.length); // 3
container.appendChild(document.createElement('span'));
console.log(liveSpans.length); // 4
</script>

Methods like getElementsByTagName() and getElementsByClassName() return HTMLCollection objects. These are live and will update as the DOM updates. The querySelectorAll() method, alternatively, returns a static NodeList which is not a live and will not update with the DOM.

let container = document.getElementById('container');
let staticSpans = container.querySelectorAll('span');
console.log(staticSpans.length); // 3
container.appendChild(document.createElement('span'));
console.log(staticSpans.length); // 3

While the NodeList returned by querySelectorAll() is not live, other NodeLists can be (e.g. the childNodes property). If you have a collection variable that may be live and you’d rather it not be, you can convert it to an array that will always be static. Both HTMLCollection and NodeList objects can be converted to arrays using Array.from().

let container = document.getElementById('container');
let staticSpans = Array.from(container.getElementsByTagName('span'));
console.log(staticSpans.length); // 3
container.appendChild(document.createElement('span'));
console.log(staticSpans.length); // 3

As a side benefit, you get access to all of the array methods (slice(), map(), etc.) by converting these collections to an array, something you might want to do whether or not you’re trying to keep it from being a live collection.

More info:

1 Like