How do I target all of the classes of classNames?

With the following code, I can target the first element of class cls-3:

var testTarget1 = parentDOM1.getElementsByClassName("cls-3")[0]; 
testTarget1.style.fill = '#fff';

This is a reset script. When I target a different element of class cls-3, this reset script will reset all of class cls-3 to a fill of #fff. (Then the selected cls-3 will be set to #000. That part already works.)

There are 50 elements of cls-3 class. How do I target all of the cls-3 elements? [0]-[50] nor [0-50] works.

This returns error of “TypeError: testTarget1 is undefined”:

var parentDOM1 = document.getElementById("cmount1"); 
var i;
for (i = 0; i < 51; i++) {
var testTarget1 = parentDOM1.getElementsByClassName("cls-3")[i]; 
testTarget1.style.fill = '#fff';
}

What else should I try?

Use the length of the array to know how to loop…

var elements = document.getElementById("cmount1").getElementsByClassName("cls-3");
for (i = 0; i < elements.length; i++) {
    elements[i].style.fill = '#fff';
}
1 Like

Instead of getElementsByClassName you can use querySelectorAll which lets you easily use the forEach method on all of them.

parentDOM1.querySelectorAll(".cls-3").forEach(function (el) {
    el.style.fill = '#fff';
});
1 Like

Thank you! I was trying to work out how to use the forEach but was being a bone head and couldn’t figure out how to get it to work. Was driving me nuts, which is why I gave him what I did…

@WebSteve, this method is more concise, and seems more efficient (at least to me).

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.