A collection is an object that represents a list of elements in the DOM (for example, NodeList
, HTMLCollection
, DOMTokenList
, etc.). A collection can be "live" or "static" (i.e. non-live). The distinction between the two is very straightforward:
What Is a Live Collection?
In a "live" collection, changes to DOM are reflected in the collection object. Following are some methods and properties that return a live collection of DOM elements:
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 |
What Is a Non-Live / Static Collection?
A "non-live" (or static) collection is the opposite of a live collection — i.e. changes in DOM do not update the collection. It can be thought of as being "fixed" to whatever the selector matches at the time the collection is created. The following method is an example of a non-live / static collection of DOM elements:
Method | Collection Type |
---|---|
querySelectorAll() |
NodeList |
Live Collection vs. Static Collection
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 we use 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 we were to dynamically add a new element with the attribute name="foo"
, we would only see the live NodeList
updated with the new element. 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.