3R - HTMLCollection vs NodeList

HTMLCollection

An HTMLCollection is a group of HTML elements that dynamically react to changes made within the DOM. It has some array-like behavior, even if it is not an actual array. Each element in the collection can be accessed by its index number, in the same way that you would with a normal array. You can also access each element with the item() method.

NodeList

A NodeList is either a group of HTML elements, or a collection of all nodes (HTML elements, text, comments, etc.), depending on which method that you're using. The method that is used also determines whether that NodeList is dynamic, meaning that it will update as the DOM changes - or if it's static.

For example, a NodeList made with querySelectorAll will create a static collection of HTML elements. But childNodes will create a dynamic collection of nodes.

Similarities/Differences

HTMLCollections and NodeLists are similar in that they both create array-like structures that contain the selected elements/nodes. HTMLCollections only contain HTML elements, and are always dynamic. Whereas NodeLists can contain all of the nodes that are associated with that selection, and can either be static or dynamic. Furthermore, you can't use any array methods on an HTMLCollection, but you can at least use forEach on a NodeList.

Summary

Knowing when to use an HTMLCollection versus a NodeList can prevent further bugs from happening to your code. For example, if you know that you don't want your "array" to change in any way once you create it, you should probably opt for a static NodeList, with a method like querySelectorAll - as opposed to an HTMLCollection, with a method like getElementsByClassName.