Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change css class property with javascript? [duplicate]

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?

like image 734
Dawid G Avatar asked Mar 07 '18 23:03

Dawid G


2 Answers

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");
like image 110
JCollier Avatar answered Oct 20 '22 09:10

JCollier


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">
like image 25
Scott Marcus Avatar answered Oct 20 '22 09:10

Scott Marcus