Override one css class with another?

I have a list with a specific li style. I want to replace the style of an individual element, but it has no 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 correctly applies the .myList li style. I am trying to remove all styles and apply foo style to one element (using jquery):

$(item).removeClass();
$(item).addClass("foo");

the element does not change color to green, but it reports that the class is set to "foo":

alert($(item).attr('class'));

so I think I don’t understand the CSS rules here, it looks like the definition of the li class just overrides everything I do, however I want the opposite to be true, I want to override the li style definition with foo. How do we do this?

thank

+3
source share
7

".myList li" , ".foo", , , . "$ (item).removeClass();" li, ul - myList, li ".myList li".

CSS:

.myList li     { background-color: yellow; }
.myList li.foo { background-color: green; }

, , .

+5

"". Chris Coyier Specificics on Specificity.

, :

ul.mylist li.foo {
  background-color: green;
}

!important ( - ) - , (), " ". . , .

+9

, !important.

.foo { background-color: green!important; }

, , , IE6 .

+2

CSS , . "" .

  • (, p, li, ul, body,...): 1
  • (,.foo,...): 10
  • Pseudo class (: hover,: focus,: active,...): 10 .
  • ID (, #wrapper, #content, #header,...): 100
  • style = "..." (, style = "color: red" ): 1000

"! important" . , IE 6 .

, "".

+2

li.foo { 
  background-color: green; 
}
+1

li , .removeClass() .

-

$(item).closest('.myList').removeClass()

myList , , , , .

, -

li.foo {background-color: green;}

, foo.

I would advise Andy Clark to read awesome CSS: Specificity Wars to fully determine the specificity of css

+1
source

Not sure if I am doing this correctly, but it looks like you are adding the class to the list item correctly, but the item still has the ".myList li" style, which is applied because there is no Delete class in the list item. Therefore, the original style takes precedence.

-1
source

Source: https://habr.com/ru/post/1749929/


All Articles