can someone tell me how can i change css class property by javascript? example:
.winner
{
background-color: white;
}
How can I change value of class winner background-color. When I write: var some = document.querySelector("winner"); I get button with class winner. I want this class not element of html. How can i get it?
There are a few ways you could do this:
On top of your current class in your .css file, you could add another class in there, and then just switch the HTML elements to belong to that new class. You would need to loop through all the elements with that class name and change them to the new name:
CSS:
.winner
{
background-color: white;
}
.winnerBlue
{
background-color: blue;
}
JavaScript:
var winnerClassElements = document.getElementsByClassName("winner");
for(var i = 0; i < winnerClassElements.length; i++)
{
document.getElementById(winnerClassElements.item(i)).className = "winnerBlue";
}
You could also add some style elements to your HTML file with this JavaScript code:
var editCSS = document.createElement('style')
editCSS.innerHTML = ".winner {background-color: blue;}";
document.body.appendChild(editCSS);
I know you didn't ask for jQuery, but if you already have it included, this is a very simple solution:
$('.winner').css("background-color" , "blue");
The way to accomplish this is to either remove the class from being applied or apply another class that overrides the first. The DOM Element classList
property is the key.
document.querySelector("input").addEventListener("click", function(){
document.querySelector("h1").classList.remove("normal");
document.querySelector("h1").classList.add("special");
});
.normal { background-color:purple; }
.special { background-color:yellow; }
<h1 class="normal">Just some text</h1>
<input type="button" value="Click to change style">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With