JS: iterating over result of getElementsByClassName using Array.forEach
No. As specified in DOM4, it's an HTMLCollection
(in modern browsers, at least. Older browsers returned a NodeList
).
In all modern browsers (pretty much anything other IE <= 8), you can call Array's forEach
method, passing it the list of elements (be it HTMLCollection
or NodeList
) as the this
value:
var els = document.getElementsByClassName("myclass");
Array.prototype.forEach.call(els, function(el) {
// Do stuff here
console.log(el.tagName);
});
// Or
[].forEach.call(els, function (el) {...});
If you're in the happy position of being able to use ES6 (i.e. you can safely ignore Internet Explorer or you're using an ES5 transpiler), you can use Array.from
:
Array.from(els).forEach((el) => {
// Do stuff here
console.log(el.tagName);
});
You can use Array.from
to convert collection to array, which is way cleaner than Array.prototype.forEach.call
:
Array.from(document.getElementsByClassName("myclass")).forEach(
function(element, index, array) {
// do stuff
}
);
In older browsers which don't support Array.from
, you need to use something like Babel.
ES6 also adds this syntax:
[...document.getElementsByClassName("myclass")].forEach(
(element, index, array) => {
// do stuff
}
);
Rest destructuring with ...
works on all array-like objects, not only arrays themselves, then good old array syntax is used to construct an array from the values.
While the alternative function querySelectorAll
(which kinda makes getElementsByClassName
obsolete) returns a collection which does have forEach
natively, other methods like map
or filter
are missing, so this syntax is still useful:
[...document.querySelectorAll(".myclass")].map(
(element, index, array) => {
// do stuff
}
);
[...document.querySelectorAll(".myclass")].map(element => element.innerHTML);
Or you can use querySelectorAll
which returns NodeList:
document.querySelectorAll('.myclass').forEach(...)
Supported by modern browsers (including Edge, but not IE):
Can I use querySelectorAll
NodeList.prototype.forEach()
MDN: Document.querySelectorAll()