Got confuse related to priority level of classes in css, i know the class added at the last has highest priority, but here in my case i thought i was wrong i am adding class dynamically to div, but classes are not working properly
<p>Click the button to add the "mystyle" class to DIV.</p>
<script>
function myFunction() {
document.getElementById("myDIV").classList.add("mystyle","hello");
}
</script>
<style>
.hello{
background-color: blue;
}
.mystyle {
background-color: red;
}
</style>
why div showing red color instead of blue ?
Working Example
Your div is red instead of blue because of your style declaration order:
.hello {
background-color: blue;
}
.mystyle {
background-color: red;
}
CSS specificity is not dependent on the order in which you apply the class to an element, but rather the order in which you declare the class in the style. In this case, you have declared .hello then .mystyle, meaning .mystyle has high specificity compared to the .hello and hence, you get the red background.
It is a problem of hierarchy:
function myFunction() {
document.getElementById("myDIV").classList.add("mystyle","hello", "red-background");
}
#myDIV.hello{
background-color: blue;
}
.mystyle {
background-color: red;
}
.mystyle {
width: 300px;
height: 50px;
background-color: red;
color: white;
font-size: 25px;
}
<p>Click the button to add the "mystyle" class to DIV.</p>
<button onclick="myFunction()">Try it</button>
<p><strong>Note:</strong> The classList property is not supported in Internet Explorer 9 and earlier versions.</p>
<div id="myDIV">
I am a DIV element
</div>
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