I am using a forEach to loop through a nodeList. My code is as follows
var array = document.querySelectorAll('items');
array.forEach(function (item) {
console.log(item);
});
And this code throws an error as
Uncaught TypeError: array.forEach is not a function
Then after reading few online blog articles i changed the code to this.
[].forEach.call(array, (function (item) {
console.log(item);
}));
Could someone please explain why it is not possible to call forEach on a nodeList and what does the above second code piece do. :)
Edit: 7/25/2017
This question does not valid for modern browsers. You can use forEach on node lists in them
Although NodeList is not an Array, it is possible to iterate on it using forEach(). It can also be converted to an Array using Array.from().
However some older browsers have not yet implemented NodeList.forEach() nor Array.from(). But those limitations can be circumvented by using Array.prototype.forEach() (more in this document).
Ref: MDN