Skip to content

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


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() { 

// So you could call
document.querySelectorAll('div').toArray().forEach(function (el) { = '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) {

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

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