re: How do I use .forEach on DOM Elements? VIEW POST

FULL DISCUSSION
 

A best practice is to convert a NodeList to a normal Array, so you can use the built-in forEach/map functions.

One ES5 way is to create a helper function, for example on the NodeList prototype:

NodeList.prototype.toArray = function() { 
  return Array.prototype.slice.call(this);
}

// So you could call
document.querySelectorAll('div').toArray().forEach(function (el) {
  el.style.color = 'pink';
})

Another popular way is to create a jQuery-ish helper function that wraps the conversion to array. This is also used in Lea Verou's bliss.js library:

function $$(sel, con) {
  return Array.prototype.slice.call((con||document).querySelectorAll(sel));
}

The modern ES7+ way is to use the ... operator:

const divs = [...document.querySelectorAll('div')];
divs.forEach(el => el.style.color = 'pink');
code of conduct - report abuse