Sam
Sam

Reputation: 4633

Javascript why use NodeList instead of using array

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?

Upvotes: 6

Views: 1557

Answers (2)

huwiler
huwiler

Reputation: 954

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.

Upvotes: 5

Travis J
Travis J

Reputation: 82267

NodeList isn't really a vanilla javascript construct so much as it is part of the DOM API. Similar to how the ecma specification will not include types such as [HtmlElement] it also will not mention NodeList.

Where you will find it is in the World Wide Web Consortium (W3C)'s documentation of the DOM api.

public interface NodeList

The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.

You can't (to my knowledge) create a NodeList. You can access one, but not create one for your own use. In this regard, that is why arrays are used in javascript.

NodeLists are going to be the result of accessing a "live" list of nodes in the DOM. This means that the list will update as you change it or as it changes automatically without any extra detecting.

Upvotes: 3

Related Questions