Welcome to the new Web Developer's Journal built with Nuxt Content!

A Look at Javascript Nodelist vs. HTMLCollection vs. DOMTokenList

Working with the DOM using vanilla Javascript has never been easier. You no longer need JQuery to select parts of a website.

Still, there are a few things you should know before you can confidently select and modify HTML elements.

The Nodelist

When you use document.querySelector, you get back a Nodelist. A Nodelist is simply a list of nodes. It can be in the DOM, but not necessarily.

A node is the basic building block of a webpage.

A Nodelist not only contains elements but also textnodes. It's not live most of the time, meaning that e.g. if you add a new node after you have got your Nodelist, your Nodelist will not necessarily update.

A live Nodelist is, for example, .childNodes. It means that if you append a new child, your childNodes Nodelist will be updated to reflect the change without you having to get the Nodelist again.

You can loop through a nodelist via forEach or a for loop using its index.

The HTMLCollection

An HTMLCollection is always live and it's always in the DOM.

document.getElementsByClassname and document.getElementsBytagname both return an HTMLCollection.

The main differenve between a Nodelist and an HTMLCollection is that an HTMLCollection can only contain HTML elements. So for example line breaks you put into your HTML code will not show up in an HTMLCollection but it will in a Nodelist.

You can loop through an HTMLCollection using either it's index or the tag name.

The DOMTokenlist

The DOMTokenlist is a special type of list. You mostly encounter it as the return value of .classList. It is a space separated list that is also index.

A DOMTokenlist has its own methods, like add(), remove(), replace(), and so on.

In contrast, .className will also return all classes but in String format and you don't have those special methods available. You do have String methods though.