TypeError: Object #<NodeList> has no method 'forEach' in javascript?

Iterating a NodeList in javascript using forEach due to temptation, you have defiantly come across TypeError: Object # has no method 'forEach'

Before digging into the error, let's try to understand what a NodeList is!

IDL Definition of NodeList is as below :

interface NodeList {
  Node               item(in unsigned long index);
  readonly attribute unsigned long   length;
};

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.

NodeList or collection of nodes are normally returned by methods like : getElementsByTagName, getElementsByTagNameNS, Node.childNodes , querySelectorAll, getElementsByClassName etc.

It's important to note that the items in a NodeList are accessible via an integral index, starting from 0.

So one would general write a normal loop like below to access the elements of a NodeList, but when we try to apply a forEach() on it, we will get an error because it has no method but that name!

for (var i = 0; i < Nodes.length; ++i) {
  var item = Nodes[i]; 
}

Simple trick to iterate NodeList is to define use Array's forEach() on NodeList, like below :

var forEach = Array.prototype.forEach;
var hrefs = document.querySelectorAll('a');
forEach.call(hrefs, function(link){ consol.log(link.src)});

If that is more, how about the below ;)

[].forEach.call( document.querySelectorAll('a'), 
function  fn(elem){ 
    console.log(elem.src);
});

Converting NodeList to List :

myList = Array.prototype.slice.call(myNodeList);

Do let me know, if with your tricks of doing the same! Happy Hacking!

Share this