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
A simpler way would be to have a css variable. The code only needs to change the value of the variable and any class that uses the variable is updated automatically.
For example:
function myFunction(c) {
document.documentElement.style.setProperty("--counterbg", c);
}
:root {--counterbg: orange;}
.counter {
width: 100px;
height:100px;
background-color:var(--counterbg);
}
#btn {
width:100px;
height:50px;
position:relative;
display:inline;
}
The variable is defined at the top of the STYLE tag and on the :root
element. The .counter style references it using var(--counterbg)
(these variables must start with --
). The js just needs to change the value of the variable. In this example, I've done three buttons that change the variable to one of three different colours.