JQuery addclass change

I have a question. How to insert a red background on only one, three and four?

$(function() {
  $("#myid li").addClass("redcolor");
});
      

.redcolor {
  background-color: red
}

.abcsize {
  font-size: 36px
}
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="myid">
  <li>One</li>
  <li class="abcsize">
    Two
    <ul>
      <li>First</li>
      <li>Second</li>
    </ul>
  </li>
  <li>Three</li>
  <li>Four</li>
</ul>
      

Run codeHide result


+3


source to share


3 answers


Use a not()

function to get all li except .abcsize and its children



$(function(){
$("#myid li").not('.abcsize,.abcsize li').addClass("redcolor");
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style> .redcolor {background-color:red}
.abcsize {font-size:36px}
</style>
<ul id="myid">
<li>One</li>
<li class="abcsize">
    Two
    <ul>
        <li>First</li>
        <li>Second</li>
    </ul>
</li>
<li>Three</li>
<li>Four</li>
</ul>
      

Run codeHide result


+4


source


Use a selector not

, make it

$("#myid > li:not(.abcsize)").addClass("redcolor");

      

Also >

only use to select children



Demo

$(function() {
  $("#myid > li:not(.abcsize)").addClass("redcolor");
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
  .redcolor {
    background-color: red
  }
  
  .abcsize {
    font-size: 36px
  }
</style>
<ul id="myid">
  <li>One</li>
  <li class="abcsize">
    Two
    <ul>
      <li>First</li>
      <li>Second</li>
    </ul>
  </li>
  <li>Three</li>
  <li>Four</li>
</ul>
      

Run codeHide result


+3


source


Use a function not()

. It is used to select all without .class

, #id

, tag

specified as a parameter to the function not()

.

$(function(){
    $("#myid>li").not(".abcsize,.abcsize>ul>li").addClass("redcolor");
});

      

+1


source







All Articles