I have a div, when I clicked on it, should turn all the elements in the .counter class to red, but at the moment it does nothing. I believe you have to run through a loop first
In addition to the given answers, I would suggest to apply style changes by adding a class to the elements and going about it via CSS. Applying inline styling takes up some more performance.
function myFunction() {
var myCounters = document.getElementsByClassName("counter")
for (var i = 0; i < myCounters.length; i++) {
console.log(myCounters[i])
myCounters[i].classList.toggle('red');
//using '.toggle' will remove the class again upon clicking the button and re-add when clicking again, and so forth. Replace .toggle by .add to only add the class if that's your use-case.
}
}
And then in your CSS
.counter {
width: 100px;
height: 100px;
background-color: orange;
}
.counter.red {
background-color: red;
}
If only doing this for a few elements on the page, the performance drawback is negligible. If you're doing this for a lot of elements, i'd suggest doing it via CSS.