5 Must-Know HTMLCollection Vs NodeList Differences In JavaScript
Learn the key differences between HTMLCollection and NodeList.
HTMLCollection is an array-like object that has a collection of document elements.
A NodeList object is a collection of document nodes (element nodes, attribute nodes, and text nodes).
1. Methods That Return HTMLCollection & NodeList
HTMLCollection
These two methods return the HTMLCollection object.
- getElementByTagName() and
- getElementsByClassName()
NodeList
Methods that return NodeList are:
- getElementsByName()
- querySelectorAll()
2. HTMLCollection (Element Nodes) vs NodeList (All Nodes)
HTMLCollection only contains element nodes such as <div>, <span>, etc.
NodeList contains element nodes, attribute nodes, text nodes, etc.
That’s kind of confusing…right.
Let’s take a look at this with a code example.
Here is the simple HTML markup.
It has a div with an id called box-wrapper which is the parent element.
The parent element has a text node and two element nodes.
<div id="box">
I'm Text Node…