What is HTMLCollection?
According to MDN Docs, HTMLCollection
is an interface that represents a generic collection of elements and offers methods and properties for selecting from the list. It groups HTML elements in an array-like manner, based on document order of elements. HTMLCollection is "live"; when the document is updated in the DOM, the HTMLCollection also updates. HTMLCollection can be accessed using document object methods, such as getElementsByClassName
or children
. Each method will retrieve the stated elements and store them in memory as an HTMLCollection containing index numbers for each child ([0], [1], [2], etc.), the individual children of which are accessible by other functions using said index numbers (element[1], element[2], element[3]).
What is NodeList?
MDN Docs defines NodeList
as objects that are collections of nodes, usually returned by properties such as Node.childNodes
and methods such as document.querySelectorAll()
. Nodes in the DOM tree consist of elements, attributes, and text nodes. NodeLists are static, meaning that once they are retrieved by the JavaScript interpreter, they will not be updated. NodeLists generated by the interpreter are also array-like, giving the objects they contain index values that allow other functions to refer to them.
Compare/Contrast
Both NodeLists and HTMLCollections allow access using their index numbers, and allow functions such as length to be used to return their "array" length. However, HTMLCollection is a dynamic collection which allows it to be updated as JavaScript continues to run, while NodeList is static and will remain the same as when it was first called in the script. For example, if an HTML document contains three elements of class name "basic", these elements can be retrieved using either document.getElementsByClassName('basic')
(which will return an HTMLCollection) or document.querySelectorAll('.basic')
(which will return a NodeList). If additional JavaScript code is written which adds another element with class name "basic" or changes the class name of another element to "basic", the "basic" HTMLCollection will update to reflect all 4 .basic
elements, while the NodeList will still only contain the original 3 .basic
elements. NodeLists will also include other types of nodes besides elements, which includes text and attributes.
Summary
NodeLists and HTMLCollections both have their place in the world of JavaScript coding, but whether or not they are the best choice to create an array-like collection of elements depends on what you need the collection for. If it is needed for variables that will remain constant, a NodeList may be preferred, but if the collection needs to change as the document is updated, an HTMLCollection is the better choice.
Sources: