A collection of DOM elements (e.g.
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.
<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
// 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
Hope you found this post useful. It was published (and was last revised ). Please show your love and support by sharing this post.