Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeList.prototype.forEach = Array.prototype.forEach;

Do you see any problems with the following:

NodeList.prototype.forEach = Array.prototype.forEach;

Normally forEach is just a property of arrays, but by setting it as a property of all NodeLists as well, there's no need to convert a NodeList to an array before you can loop through its nodes with forEach.

like image 987
Web_Designer Avatar asked Mar 07 '13 09:03

Web_Designer


People also ask

Can you do forEach on a NodeList?

forEach() The forEach() method of the NodeList interface calls the callback given in parameter once for each value pair in the list, in insertion order.

What is difference between NodeList and array?

A NodeList may look like an array, but in reality, they both are two completely different things. A NodeList object is basically a collection of DOM nodes extracted from the HTML document. An array is a special data-type in JavaScript, that can store a collection of arbitrary elements.

How come I can't use forEach or similar array methods on a NodeList?

Why can't I use forEach or map on a NodeList? NodeList. prototype contains the item method, but none of the Array. prototype methods, so they cannot be used on NodeLists.

What is array prototype forEach call?

The JavaScript forEach method (Array. prototype. forEach) is a function that iterates through an array and will execute a callback that is provided to it on each iteration. The forEach method was added in ECMAScript 5 specification and has full browser and node. js support.


2 Answers

It's often not a good idea to extend the functionality of DOM through prototypes, especially in older versions of IE (article).

However, you can simply use Array.prototype.forEach even without adding it to the prototype chain or converting your NodeList into an array:

var list = document.querySelectorAll(".some.query");
Array.prototype.forEach.call(list, function(el){ /* ... */ });

/* or */
var forEach = function(ctn, callback){
    return Array.prototype.forEach.call(ctn, callback);
}
forEach(list, function(el){ /* ... */ });

See also MDN: Why can't I use forEach or map on a NodeList.

like image 177
Zeta Avatar answered Oct 02 '22 19:10

Zeta


If you're working on a library that will be used by other people then it's not a good idea to do this.

If it's just your own code (i.e.. a website) then I guess it's no big deal. You should probably guard it though because in the future browsers will support NodeList.prototype.forEach natively (Chrome does already).

if (!NodeList.prototype.forEach) {
  NodeList.prototype.forEach = Array.prototype.forEach;
}
like image 45
DaveJ Avatar answered Oct 02 '22 18:10

DaveJ