HTMLCollection vs NodeList

Harsh
3 min readAug 12, 2021

There is a lot of fuss going around the topic of HTML Collection vs Node List. People are confused between the two and the only question which arises is which is better and why? So let’s try to understand the topic in detail with some theory and examples.

Definition

So we can group elements by their class name in two ways:

  1. document.getElementsbyClassName(): It returns a live HTML Collection representing an array-like object of all child elements which have all of the given class names.
  2. document.querySelectorAll(): It returns a static Node List representing a list of the document’s elements that match the specified group of selectors.

Now let’s try to understand the difference more clearly with hands-on with both things.

Example

Let’s take a basic HTML structure that contains a list of cars.

From the above HTML code, we will see a list of Cars that we added to the page as shown below.

Now let’s try to access the list using the query selector and the class name. After that, we will try to add a new car through the java script itself.

After executing the whole code we got the following results in our console log.

So here is the thing, after we added a new car into the list and tried to get the items in the list again there was a difference in the number. In the HTML Collection, we could see 4 car items but in the Node List, we could only see 3 car items. This happened because as we know HTML Collection returns the live array list whereas in the case of Node list, it didn’t realize there was a change in the list i.e. Static node list which is the big difference between the two and makes it different from each other

Conclusion

To sum things up, I would like to say none of them is better than another because they should be used according to the structure that we have in our HTML and our needs but we should keep this huge difference in mind whenever we choose between the two.

If you have learnt something from this blog then do click the clap button and if you have any doubt(s) regarding this, you can leave a comment or contact me on LinkedIn.

--

--