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?
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?
Share Improve this question edited Dec 20, 2014 at 0:02 Mark Amery 156k90 gold badges430 silver badges472 bronze badges asked Feb 14, 2014 at 0:27 SamSam 4,65315 gold badges51 silver badges84 bronze badges 1- 1 "I have read the document" - which document? – Mark Amery Commented Dec 20, 2014 at 0:01
2 Answers
Reset to default 5You 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.
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.