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!
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.
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:
- Returns the number of items that are in the collection
- Returns a specific element at the index position of the number provided as an argument.
- Returns a specific element whose ID/Name matches the argument passed in the parenthesis.
- The argument should be in quotes
The HTMLCollection interface represents a generic collection (array-like object similar to arguments) of elements (in…
Although NodeList is not an Array, it is possible to iterate over it with forEach(). It can also be converted to a real…
HTML DOM nodeType Property
Element Object Get the node type of the body element: Try it Yourself " More "Try it Yourself" examples below. The…