views:

100

answers:

5

in some cases, this will not work:

("#id").addClass("class");

whereas this will:

("#id").css('color','Blue');

why would it fail and how to add class otherwise?

+1  A: 

If there is an inline styling applied then addClass may fail.

Sample

$(function() {
    $("#ul1 li a" ).hover(
       function () {
           $(this).css('color','red');
       }, 
       function () {
           $(this).css('color','blue');
       }
    );
});

<ul id="ul1">
    <li>
        <a href="#">test
        </a>
    </li>
</ul>

You can also use toggleClass method to do this.

rahul
Or even a stronger CSS rule. It's a css fail. +1.
Kobi
in my case i have inline <li> <a> </li> how can i change hover color on the a tag with the css function?
zsharp
+1  A: 

One possibility is that the class has pre-existing styles applying to it that supersede the properties of the class you have added. Though, I only suggest this because you show using .css as a tactic that always works. If the object is simply not getting the class added to it at all, I'm not sure.

Tegeril
A: 

This is probably because when a class is already applied, it won't be applied again. Jquery checks that. The css method applies without looking at what are the previous styles.

Sarfraz
+3  A: 

Key concept: CSS Specificity

From CSS Specificity: Things You Should Know:

  1. Specificity determines, which CSS rule is applied by the browsers.
  2. Specificity is usually the reason why your CSS-rules don’t apply to some elements, although you think they should.
  3. Every selector has its place in the specificity hierarchy.
  4. If two selectors apply to the same element, the one with higher specificity wins.
  5. There are four distinct categories which define the specificity level of a given selector: inline styles, IDs, classes+attributes and elements.
    ...

Nice little cheatsheet:

CSS Specificity Cheat Sheet

micahwittman
+1. very nice answer
rahul
A: 

Do one thing, try something like

 ("#id").addClass("test");

Now check with Firebug / IE dev toolbar if this dummy "test" class is getting applied or not.

Wondering