Stigma of forEach on nodelist

Hey Guys,

Today i would like to share my thoughts on executing forEach function of Javascript on the nodeList. Now many of you might be aware of forEach loop which is another version of “For Loop” particularly for an array with a callback attached to it.

var array = [ini,mini,myni, moh];

array.forEach(function(ele, index) {
  console.log(ele);
});

Above is a simple code that just iterates over the array and console logs’ the element.

Now the problem is that its exclusively for an array. When you try to execute it on the nodeList which we get either by using querySelectorAll or something like getElementsByTagName. Well nodeList is a list of nodes that we get by querying the DOM.

document.querySelectorAll('div')
//It will list all the divs inside the document in the form of a nodelist.

Now the problem is if i do nodelist.forEach in Chrome, it works fine but in firefox it throws me an error saying forEach is not defined. Let’s come to the solution. What we can do is to map the forEach from nodelist to an array by

[].forEach.call(document.querySelectorAll('div'), function(ele, index) {
   console.log(ele.innerHTML);
});

This is one solution. But it has fallbacks. What we can do is define the forEach function for nodelist in our code which will iterate over the elements just like the forEach function.

NodeList.prototype.forEach = function(array, callback)  {
  for (var i=0; i< array.length; i++)  {
    callback.call(array[i], i);
  }
}
document.querySelectorAll('div').forEachfunction(ele, index){});

So this is the whole deal.

Hope you liked it. Happy coding.

Author: shellophobia

just passing time here.. and enjoying

Leave a comment