Magical JavaScript Live Collection

JavaScript live collection is a subject that is rarely talked about. Earlier I had written about a caveat when using them. It did help people but one of the problem is that most didn't understand what was happening and thought it was just a quirk in JavaScript.

Let me make things clear. HTML Live collection with JavaScript is not a quirk. It is a feature and you can make good use of it. Let's see how it works.

Remember the DOM APIs document.getElementsBy*? When these methods are used, it is common to use a for loop to go through each element to perform some task. Even though the result of these methods can be treated like Arrays they are not arrays. What they are is an HTML collection. The power and main difference between these and a regular array is that they are directly tied to the DOM. If you update the DOM, the collection is updated accordingly.

Here is one little experience. We are going to create a live collection, and watch it update without any explicit interaction on our part.

var collection = document.getElementsByClassName("collection"); 

Let's say I declare this variable and there are no elements with class name 'collection'. Obviously, this will return an empty array like collection. If I check the length, it will be zero

> 0

Now let's create an element with said class name and append it to the DOM and see what happens to our collection.

var element = document.createElement("p");
element.className = "collection";

// Checking the length
> 1

> <p class="collection"></p>

The new element found its way into our collection array without having to re-fetch it from the DOM.

This neat little feature can be very useful. You can have a variable that keeps track of, let's say, active users without having to constantly check the DOM or having to pop values in and out of an array.


There are no comments added yet.

Let's hear your thoughts

For my eyes only