I want to iterate over some DOM elements, I\'m doing this:
document.getElementsByClassName( \"myclass\" ).forEach( function(element, index, array) {
//do s
The result of getElementsByClassName()
is not an Array, but an array-like object. Specifically it's called an HTMLCollection
, not to be confused with NodeList
(which has it's own forEach() method).
One simple way with ES2015 to convert an array-like object for use with Array.prototype.forEach()
that hasn't been mentioned yet is to use the spread operator or spread syntax:
const elementsArray = document.getElementsByClassName('myclass');
[...elementsArray].forEach((element, index, array) => {
// do something
});