A collection of DOM elements (e.g. NodeList
, HTMLCollection
, DOMTokenList
, etc.) can either be "live" or "non-live" depending on the method you use to retrieve the collection. A live collection is one where changes in DOM are reflected in the collection while a non-live (or static) collection is the exact opposite of that.
Please note that live collections can have performance costs because every time you access a member of a live collection, the browser has to traverse the entire document tree to find the specific element. This could be especially costly when you choose to iterate over a live collection. In such cases, it is better to either convert the collection to an array or use a non-live / static collection instead.
To demonstrate the difference between live and non-live JavaScript collections, let's consider the following HTML markup:
<form id="my-form">
<input type="radio" name="foo" value="bar" />
<input type="radio" name="foo" value="baz" />
</form>
Now, let's suppose you're using the following methods to get a collection of NodeList
:
// non-live NodeList
const staticList = document.querySelectorAll('[name="foo"]');
console.log(staticList.length); // output: 2
// live NodeList
const liveList = document.getElementsByName('foo');
console.log(liveList.length); // output: 2
If you were to dynamically add a new element with the attribute name="foo"
, you would only see the live NodeList
updated with the new element and not the static collection. For example:
// add new radio button
const radiobox = document.createElement('input');
radiobox.type = 'radio';
radiobox.name = 'foo';
radiobox.value = 'qux';
document.getElementById('my-form').appendChild(radiobox);
console.log(staticList.length); // output: 2
console.log(liveList.length); // output: 3
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.