Very interesting though it is weird behaviour.
var elem = document.getElementsByClassName("cls")[0];
elem.style.backgroundColor = "yellow"; // It'll become inline property
.cls {
width: 100px;
height: 100px;
background-color: #ff0000;
}
.cls:hover { background-color: #0000ff; }
<div class="cls"></div>
When we are applying background-color
from Javascript, it'll become inline property and taking high priority over other properties and even overriding background-color
from hover
effect.
For a POC, look at this
.cls {
width: 100px;
height: 100px;
background-color: #ff0000; }
.cls:hover { background-color: #0000ff; }
<div class="cls" style="background-color: yellow"></div>
Now, i'm applying background-color
from inline
and here also it is taking high priority over css
styles.
Solution for this cause is, adding !important on hover
var elem = document.getElementsByClassName("cls")[0];
elem.style.backgroundColor = "yellow";
.cls {
width: 100px;
height: 100px;
background-color: #ff0000;
}
.cls:hover { background-color: #0000ff !important; }
<div class="cls"></div>
UPDATE
As @Mr_Green said, adding !important
property is not best practice, instead we can add one more class will also solves your problem.
var elem = document.getElementsByClassName("cls")[0];
elem.classList.add('secondary');
.cls {
width: 100px;
height: 100px;
background-color: #ff0000;
}
.secondary {
background-color: #000000;
}
.secondary:hover {
background-color: #0000ff;
}
<div class="cls"></div>
Hope this helps :)