I want to iterate over some DOM elements, I\'m doing this:
document.getElementsByClassName( \"myclass\" ).forEach( function(element, index, array) {
//do s
This is the safer way:
var elements = document.getElementsByClassName("myclass");
for (var i = 0; i < elements.length; i++) myFunction(elements[i]);
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()
It does not return an Array
, it returns a NodeList.
Here is a test I created on jsperf: https://jsperf.com/vanillajs-loop-through-elements-of-class
The most perfomant version in Chrome and Firefox is the good old for loop in combination with document.getElementsByClassName:
var elements = document.getElementsByClassName('testClass'), elLength = elements.length;
for (var i = 0; i < elLength; i++) {
elements.item(i).textContent = 'Tested';
};
In Safari this variant is the winner:
var elements = document.querySelectorAll('.testClass');
elements.forEach((element) => {
element.textContent = 'Tested';
});
If you want the most perfomant variant for all browsers it might be this one:
var elements = document.getElementsByClassName('testClass');
Array.from(elements).map(
(element) => {
return element.textContent = 'Tested';
}
);
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
});