Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript why use NodeList instead of using array

Tags:

javascript

dom

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?

like image 574
Sam Avatar asked Feb 14 '14 00:02

Sam


People also ask

What is difference between NodeList and array?

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.

Is a Node list an array?

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.

What is the difference between HTMLCollection and NodeList?

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.

What is the difference between Node and NodeList?

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 .


1 Answers

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.

like image 151
huwiler Avatar answered Oct 03 '22 00:10

huwiler