Search code examples
javascriptarraysforeachnodelist

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.


Solution

  • 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.