Search code examples
javascriptjquerycssaddclasscss-specificity

Why CSS .addClass is not applying proper style per specificity?


I understand the concept of css specificity. Here is my situation:

I have a style for class called "success". This simply makes colors green...etc. Now I have 2 separate css files that defines .success (they define a different style). Let's call these Site.css and Page.css.

The class in Site.css is simply:

.success { color: green; }

The class in Page.css is more specified:

#MainRegion div .resultPanel .success { background-color: green; }

Now in javascript (using jquery), I add a class like so:

$("#MainRegion div .resultPanel").addClass("success");

Now, when I inspect this using a browser-debugger (F12), I can see that the Site.css style was applied (rather than the Page.css). I thought the class defined in Page.css has more specificity thus it should be the one that is called. Am I missing something about my understanding of how css specificity works?


Solution

  • You are missing something. This line of code

    $("#MainRegion div .resultPanel").addClass("success");
    

    returns

    #MainRegion div .resultPanel.success
    
    <div class="resultPanel success"></div>
    

    and not

    #MainRegion div .resultPanel .success
    
    <div class="resultPanel">
        <div class="success"></div>
    </div>
    

    So depending on what you want, you can change your css or the js to target the correct element

    if your css is

    #MainRegion div .resultPanel.success { background-color: green; }
    

    then your js will work as expected