HTMLCollection vs NodeList

In this page, I’m going to break down the difference between HTMLCollection and NodeList, how the DOM gives them back to us, and why it actually matters when writing JavaScript.

Back

What Is an HTMLCollection?

An HTMLCollection is basically a group of HTML elements that the DOM gives back to you. It looks and acts kind of like an array, but it’s not actually a real JavaScript array. You can still access items using an index, like [0], [1], etc.

One important thing I noticed is that HTMLCollections are usually live. That means if something changes in the DOM, like adding or removing elements, the collection updates automatically without you doing anything.

Methods like getElementsByClassName() and getElementsByTagName() return an HTMLCollection.

What Is a NodeList?

A NodeList is also a collection, but it’s a little more flexible. Instead of only holding HTML elements, it can contain different types of nodes like text and comments. So it’s not limited to just elements.

Another thing is that NodeLists can be either live or static. For example, querySelectorAll() gives back a static NodeList, which means it does NOT update automatically. But something like childNodes gives a live NodeList.

So with NodeList, it really depends on how you got it from the DOM.

Differences and Similarities

Both HTMLCollection and NodeList are similar because they are array-like and come from the DOM when selecting multiple things. You can loop through them and access items by index. But they are not actual arrays, so they don’t always have full array methods.

The biggest difference is what they contain and how they update. HTMLCollection only contains HTML elements and is almost always live. NodeList can contain more than just elements and can either be live or static depending on the method used.

For example:
getElementsByTagName() → HTMLCollection (live)
querySelectorAll() → NodeList (static)
childNodes → NodeList (live)

Summary

Overall, both HTMLCollection and NodeList are useful when working with the DOM, but you have to know which one you’re dealing with. If you expect something to update automatically and it doesn’t, it’s probably a static NodeList.

Understanding the difference makes it easier to avoid bugs and helps you write cleaner JavaScript when selecting and working with elements on a page.