3R - HTMLCollection vs NodeList

Define/Explain the HTMLCollection

HTMLCollection refers to array like collection of HTML elements that are collected from the page. These elements are dynamic and and update to reflect the current state of the document. As with arrays, the items in this object are referenced by using the brackets [] with a number inside to correlate with the item you wish to access. Items can also be accessed with item() or namedItem() (for a specific name or ID) You can also use the length property to find out the number of items in this object. HTMLCollections are created by using properties like: getElementsByTagName or getElementsByClassName.

Define/Explain the NodeList

Nodelists are a group of element nodes created by using the property querySelectorAll or childNodes. As with arrays, the items in this object are referenced by using the brackets [] with a number inside to correlate with the item you wish to access. Many times Nodelists are static - meaning they do not update as the DOM updates. These are created with the querySelectorAll method. When using the childNodes method, a live list is created. You can also use the length property to find out the number of items in this object.

Explain Differences and/or Similarities

HTMLCollections can only contain HTML elements and a Nodelist can contain anything. Both work on an array type structure for accessing the elements inside it. While both can be accessed by an index number, HTMLCollections can also be accessed by specific names or IDs as well. HTMLCollections are dynamic lists while Nodelists are usually static. The length method can be used for both types to get the number of items in the object.

Summary

Both HTMLCollections and Nodelists are important and very useful objects within JavaScript. Between these two items, the programmer can easily collect a group of element, attribute, or text nodes from a web page that can then be updated, added to, or removed. It allows an efficient way to grab the data and work with it.

References: