A "live" collection in JavaScript is a collection of DOM elements where changes to DOM are reflected in the collection object (such as when a new element is added or an existing one is removed or updated).
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.
Following are some methods and properties that return a live collection of DOM elements in JavaScript:
Property / Method | Collection Type |
---|---|
parentNode.children |
HTMLCollection |
Node.childNodes |
NodeList |
Element.classList |
DOMTokenList |
HTMLLinkElement.relList |
DOMTokenList |
HTMLAnchorElement.relList |
DOMTokenList |
HTMLAreaElement.relList |
DOMTokenList |
HTMLMediaElement.audioTracks |
AudioTrackList |
HTMLMediaElement.textTracks |
TextTrackList |
HTMLMediaElement.videoTracks |
VideoTrackList |
document.forms |
HTMLCollection |
HTMLFormElement.elements |
HTMLFormControlsCollection |
getElementsByClassName() |
HTMLCollection |
getElementsByTagName() |
HTMLCollection |
getElementsByName() |
NodeList |
For example, let's consider you have the following HTML markup:
<form id="my-form">
<input type="radio" name="foo" value="bar" />
<input type="radio" name="foo" value="baz" />
</form>
Imagine you use the Document.getElementsByName()
method to get a collection of NodeList
containing all form
elements having the attribute/value combination name="foo"
, like so:
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 see how the live NodeList
gets updated with the new element:
// 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(liveList.length); // output: 3
This post was published 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.