NodeList & HTML Collections, What Are They?

Karan S. Chauhan
3 min readSep 10, 2020

--

At the start of Mod 3 at Flatirons software engineering program, it was confusing to see Nodelists and HTML collections, opposed to the traditional arrays that became familiar at that point.

But after some practice and research, it was simple to understand the differences between the two. This article is about a simple comparison between Nodelists and HTML collections, so that incoming programmers won’t have to be puzzled when they come across them. Let’s start!

NodeLists

source: https://www.w3schools.com/jsref/prop_node_nodetype.asp

There are many types of nodes, this table from W3 Schools display a variety of 12 nodes. In my personal experience in Flatiron’s bootcamp, my cohort and I were mostly occupied with the Element, Attr, and Text nodes.

Simply, Nodelists are a collection of nodes, whether they are elements, attributes, texts, etc… It’s very easy to misunderstand them since they look alike. But many methods that work on arrays won’t work on Nodelists.

There are a few ways to work with them, the ‘forEach()’ method works on Nodelists. Also, if you’re like me and would much rather work with an actual array, you can use the ‘Array.from()’ method to change the NodeList to an array.

Some tips: live vs static

  • Some methods will return a Nodelist successfully, like document.querySelectorAll(), however this comes with a drawback. If you make any changes to the DOM after calling this method, the data won’t change. This would be an example of a ‘Static’ method.
  • Methods that will dynamically update when changes are made are called ‘live’ methods, a perfect example is the ‘.childNodes’ method.

HTML Collections

Generally speaking, an HTML Collection is a collection of elements that were selected by the appropriate query.

Unlike some of the Nodelist methods that return a ‘static’ result, HTML Collections are ‘live’, meaning they will dynamically update as soon as there’s a change to the DOM.

Personally, I’ve always used the ‘Array.from()’ method on HTML Collections, just so I know I’m working with an actual array. But there are some methods that can be used specifically for the HTML Collection, for example:

  1. HTMLCollection.length
  • Returns the number of items that are in the collection

2. HTMLCollection.item()

  • Returns a specific element at the index position of the number provided as an argument.

3. HTMLCollection.namedItem()

  • Returns a specific element whose ID/Name matches the argument passed in the parenthesis.
  • The argument should be in quotes

Resources:

https://dev.to/jharteaga/difference-between-htmlcollection-and-nodelist-25bp#:~:text=At%20first%20hand%20the%20HTMLCollection,that%20occur%20in%20our%20HTML.

--

--

No responses yet