Search code examples
javascriptprototype

How to iterate through a nodeList functional style


I frequently want to iterate through a NodeList with forEach or map. My simplified code works like this:

var nodeListMap = Array.prototype.map;
var els = document.querySelectorAll('.classname');
nodeListMap.call(els, function(el){...});

This works fine. However, I'd prefer not have to map.call, but if I do this...

var nodeListMap = Array.prototype.map.call;
var els = document.querySelectorAll('.classname');
nodeListMap(els, function(el){...});

Then it returns

TypeError: object is not a function

How can I modify the code so I simply do nodeListMap(array, fn)?


Solution

  • After six years the map and forEach methods are available on NodeLists on most browsers (the odd duck being IE usual). Check forEach nodeList support on caniuse.

    If older browser support is needed, I have settled on the following for brevity and clarity (ES6+):

    const els = Array.from(document.querySelectorAll('.selector'));

    Then, you can simply iterate as...

    els.forEach(el => doSomething)