Css class priority when Adding Dynamic Class

Pardeep Jain

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

Kevin

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Css class priority when Adding Dynamic Class

From Dev

CSS Transition works when adding class, but not removing it

From Dev

Adding CSS class as a style

From Dev

Adding CSS Class with execCommand()

From Dev

Regex for adding CSS class

From Dev

dynamic or adaptable class in css

From Dev

dynamic or adaptable class in css

From Dev

dynamic css class in angular

From Dev

Why is css transition not working when adding class using javascript / jQuery?

From Dev

Adding a css-class to a div when scrolling down

From Dev

CSS Transition not firing when adding class to body (Firefox)

From Dev

CSS transition not working when adding class via jquery

From Dev

CSS Animation, working adding class, but not removing the class

From Dev

removing and adding css class onclick

From Dev

Adding a CSS class is not rendered by the browser

From Dev

Adding a css class to select in Rails

From Dev

ng-class not adding the class when true

From Dev

UnsupportedOperationException when adding class to Collection

From Dev

Adding a class when images are loading

From Dev

UnsupportedOperationException when adding class to Collection

From Dev

Tapestry pagelink with dynamic css class

From Dev

Dynamic content depending on css class

From Dev

Vue Js Adding Dynamic Class name

From Dev

Create dynamic nested class and adding it as a property in a dynamic Type

From Dev

How do I give a CSS class priority over an id?

From Dev

Adding a CSS class to element on ng-click

From Dev

Adding CSS class or style to p:message

From Dev

Adding icon image to css class for html elements

From Dev

Adding animation CSS class with Jquery for twitch status

Related Related

HotTag

Archive