3

I have a question How to insert background red color only on 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>

2

3 Answers 3

4

Use not() function to get all li's except for the .abcsize and his 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>

Sign up to request clarification or add additional context in comments.

Comments

3

Use not selector, make it

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

Also use > for only selecting the 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>

3 Comments

and what if i need to apply on <li>First</li> too?)
@anete.anetes yes, realized it as soon as I posted it.
madalin ivascu and gurvinder372 I tried ur jquery not work.
1

Use not() function. Its used to select all without .class, #id, tag given as parameter on not() function.

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

2 Comments

Whats your result? BTW, then try with $("#myid li:first-child, #myid li:last-child", #myid li:nth-child(3)).addClass("redcolor"); });
Sorry brother I forget to save the html

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.