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?
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?
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.
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.
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.
Key concept: CSS Specificity
From CSS Specificity: Things You Should Know:
- Specificity determines, which CSS rule is applied by the browsers.
- Specificity is usually the reason why your CSS-rules don’t apply to some elements, although you think they should.
- Every selector has its place in the specificity hierarchy.
- If two selectors apply to the same element, the one with higher specificity wins.
- There are four distinct categories which define the specificity level of a given selector: inline styles, IDs, classes+attributes and elements.
...
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.