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

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


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.


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;}


As Zeta mentioned, it would be better to use a convenience function. This version, however, will allow you to give it context.

var forEach = function(list, callback, context){  return Array.prototype.forEach.call(list, callback, context);};