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