Iterating a NodeList in JavaScript using forEach due to temptation, you have definitely 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 generally 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 by that name!
for (var i = 0; i < nodeList.length; i++) {
// do something with nodeList[i]
}
Simple trick to iterate NodeList is to use Array’s forEach() on NodeList, like below:
var forEach = Array.prototype.forEach;
var hrefs = document.querySelectorAll('a');
forEach.call(hrefs, function(link) {
console.log(link.src);
});
If that is more, how about the below ;)
[].forEach.call(document.querySelectorAll('a'), function(elem) {
console.log(elem.src);
});
Converting NodeList to Array:
myList = Array.prototype.slice.call(myNodeList);
Do let me know your tricks of doing the same! Happy Hacking!
About Hemanth HM
Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.