What Is a Static Collection in JavaScript?

A "non-live" (or static) collection in JavaScript is a collection of DOM elements where changes in DOM do not update the collection (as opposed to a live 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

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" />

Imagine you use the Document.querySelectorAll() method to get a collection of NodeList containing all form elements having the attribute/value combination name="foo", like so:

const staticList = document.querySelectorAll('[name="foo"]');

console.log(staticList.length); // output: 2

If you were to dynamically add a new element with the attribute name="foo", you would see how the new element is absent from the NodeList:

// add new radio button
const radioBox = document.createElement('input');
radioBox.type = 'radio';
radioBox.name = 'foo';
radioBox.value = 'qux';


console.log(staticList.length); // output: 2

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.