I have read the document and did not fully understand the advantage of using NodeList.
Since it's like array (I knew it's not array), what are advantages of using NodeList instead?
The key way to think about NodeLists vs. Arrays: NodeLists are a language-agnostic way to access DOM elements, and Arrays are a JavaScript object you can use to contain collections of stuff.
Note: Although NodeList is not an Array , it is possible to iterate over it with forEach() . It can also be converted to a real Array using Array.
An HTMLCollection is a collection of document elements. A NodeList is a collection of document nodes (element nodes, attribute nodes, and text nodes). HTMLCollection items can be accessed by their name, id, or index number. NodeList items can only be accessed by their index number.
A Node is, roughly, a distinct object with some internal state. The name Node implies that the object can be or is a member of some collection, often but not always a list. A NodeList is just a linear list of nodes. There are other types of collection that can contain nodes, such as a Map or Graph or Tree .
You only use a NodeList when one is returned by the DOM. Why doesn't the DOM return an Array or at least a type that has Array in its prototype chain? Because the DOM is designed to not depend on anything language specific. All types returned by the DOM API will be host types rather than native types. This allows the DOM to be language agnostic and not dependent on any specific language construct.
You can, of course, use Array methods on a NodeList via call or apply. E.g.
Array.prototype.map.call(nodeList, function (a, index) { ... });
Another interesting attribute of "live" NodeLists is the data binding maintained between NodeList and that API call that returned it. This data binding causes the NodeList to update automatically in response to DOM manipulations that would have effected the nodes returned by the call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With