javascriptjqueryaddclass

How to use addClass() to prepend the class in the element's class list


I hav a div in my HTML

    <button id="abc" class="btn btn-primary btn-block"></button>

I need to add a class 'alert-danger' on mouseover. So i used the following code

    $(document).on("mouseover","#abc",function()
    {
          $(this).addClass("alert-danger");
    });

This works fine and it appends the class at the end of the class list as below

    <button id="abc" class="btn btn-primary btn-block alert-danger"></button>

But the problem is 'btn' and 'alert-danger' classes have some common css rules. 'btn' takes priority (as it is first in the list) and disables the rules of 'alert-danger'.So my button should be like this with 'alert-danger' class as the first in the classlist.

    <button id="abc" class="alert-danger btn btn-primary btn-block"></button> // My requirement 

How to modify my addClass() in order to prepend the class instead of appending it.


Solution

  • An alternative to your requirement.

    You can mark !important to css property in alert-danger class, which will prioritize the css effect as per your requirement.

    Check this fiddle demo.

    Excerpt:

    .alert-danger{
        background: #FF0000 !important;
        color: blue !important;
    }