I have a list, with an li style defined. I want to replace the style of an individual element, but it doesn’t seem to have any visual effect. Example:
.myList li {
background-color: yellow;
}
.foo {
background-color: green;
}
<ul class='myList'>
<li>Hello</li>
</ul>
When I add an item to the list, it has the .myList li style applied properly. I try now to remove all styles and apply the foo style to a single item (using jquery):
$(item).removeClass();
$(item).addClass("foo");
the item does not change color to green though, but this reports the class is set to ‘foo’:
alert($(item).attr('class'));
so I guess I’m not understanding css rules here, looks like the li class definition is just overriding whatever else I do, however I want the reverse to be true, I want to override the li style definition with foo. How do we do this?
Thanks
The “.myList li” selector is more specific than the “.foo” selector, so when both rules apply, the item will be yellow. When you do “$(item).removeClass();” you remove any class names from the li, but if the ul still has it’s “myList” class name, then the li will still get the styles from the “.myList li” selector.
One way to change the CSS would be to:
Then it is clear that the second rule is more specific than the first.