I want to iterate over some DOM elements, I\'m doing this:
document.getElementsByClassName( \"myclass\" ).forEach( function(element, index, array) {
//do s
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);