JavaScript JavaScript and the DOM Getting a Handle on the DOM Using CSS Queries to Select Page Elements

Sergi Oca
Sergi Oca
7,981 Points

Understanding the difference between an HTMLCollection and a NodeList.

So in this video I realized, querySelectorAll returns a "nodeList", while getElementsByTagName (didn't check-ByClassName but I assume it's the same) returns an HTML Collection. I have read the official explanation and I don't really understand it. Is this important to understand? Is there a major difference between the two?

2 Answers

The most simplest answer is that both a NodeList and HTMLCollection are collections of DOM nodes. The difference is that while a NodeList can contain any node type, the HTMLCollection is going to only to contain any node Element.

So what is the difference between a node element and a node type?

Nodes: in the DOM, everything is a node and every node is an object. The name node is used as a generic term, for everything.

Element: is one specific type of node. It can be a list item, a div, the body, the window, whatever, but its a specific type.

Now we can see what the difference between a nodeList is and what a node element is:

In the end, one is general and one is specific lists of nodes. It's important to know simply because you should know what you are returning and for more advanced JavaScript issues such as speed, in the case of static NodeLists vs Live NodeLists.

By the way this is an awesome question!

Sergi Oca
Sergi Oca
7,981 Points

Thank you for a great answer, now I get it.

Any Time! Glad I could help.

Leoben 1987
Leoben 1987
1,574 Points

When it comes to speed, would I be correct to assume it is faster to ┬┐retrieve? elements using a selector that generates an HTMLCollection instead of a NodeList? So getElementsByXXX is faster than querySelectorAll if applied to the same purpose.

Leoben 1987 Yes, using something like getElelemntsByTagName() is faster than say querySelectorAll. This is because of the difference between static and live node lists objects. In all honestly, unless you are doing something huge you'll probably won't notice a difference, but It's good to know.

here is a site that tests this test

Steven Parker
Steven Parker
203,986 Points

:point_right: HTMLCollection and NodeList differ in potential contents and available methods.

An HTMLCollection should contain only elements, has a namedItem method, and allows item indexing by number or name.

A NodeList can contain elements along with other types of nodes (such as text blocks), and the items can only be indexed by number.

So they are very similar, but while a NodeList could possibly contain only elements, you could not use the namedItem method on it, or index into it using names as indices.