6

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?

1
  • 1
    "I have read the document" - which document?
    – Mark Amery
    Commented Dec 20, 2014 at 0:01

2 Answers 2

5

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.

2
  • 1
    In the case of document.querySelectorAll, is a non-live NodeList returned purely because it is independent as well, or is there other benefits to having a NodeList?
    – Robert
    Commented Jun 13, 2014 at 21:24
  • 3
    In the cases where non-live Nodelists are returned (I think querySelectorAll is the only case), there are no benefits to Nodelist over Array other than API consistency and decoupling of language specific constructs.
    – huwiler
    Commented Jul 18, 2014 at 19:03
3

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.