alioua walid
alioua walid

Reputation: 247

jQuery - removeClass() applied to all classes except one

I want to remove the class .active from all the anchors except the <a> of child number 2; I don't know why this is not working.

/*Remove ".active" from all the anchors except child number 2 */
$("#list li:not(li:nth-child(2) a)").removeClass("active");
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>


<style>
  .active {
    color: red;
  }
</style>


<div id="list">
  <ul>
    <li><a class="active" href="#">One</a></li>
    <li><a class="active" href="#">Two</a></li>
    <li><a class="active" href="#">Three</a></li>
  </ul>
</div>

Thanks everyone.

Upvotes: 0

Views: 45

Answers (3)

Michael Eugene Yuen
Michael Eugene Yuen

Reputation: 2528

I think this one is better to read:

$("#list li a").not('#list li:nth-child(2) a').removeClass("active");
.active{
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="list">
<ul>
    <li><a class="active" href="#">One</a></li>
    <li><a class="active" href="#">Two</a></li>
    <li><a class="active" href="#">Three</a></li>
</ul>

</div>

Upvotes: 1

David Thomas
David Thomas

Reputation: 253318

Your selector was written wrongly, I'm assuming this was a typo resulting from a later edit of the selector, given the misplaced ) character. So, rather than:

$("#list li:not(li:nth-child(2) a)").removeClass("active");

Instead use:

$("#list li:not(li:nth-child(2)) a").removeClass("active");

Your original selector was looking for an <li> element that was not the second-child of its parent and, also, was not an <a> element; this is true for all <li> elements.

/*Remove ".active" from all the anchors except child number 2 */
$("#list li:not(li:nth-child(2)) a").removeClass("active");
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>


<style>
  .active {
    color: red;
  }
</style>


<div id="list">
  <ul>
    <li><a class="active" href="#">One</a></li>
    <li><a class="active" href="#">Two</a></li>
    <li><a class="active" href="#">Three</a></li>
  </ul>

</div>

Upvotes: 1

Ibrahim Khan
Ibrahim Khan

Reputation: 20740

You selector is wrong. You should use #list li a:not(li:nth-child(2) a) instead.

$("#list li a:not(li:nth-child(2) a)").removeClass("active");
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

<style>
  .active {
    color: red;
  }
</style>

<div id="list">
  <ul>
    <li><a class="active" href="#">One</a></li>
    <li><a class="active" href="#">Two</a></li>
    <li><a class="active" href="#">Three</a></li>
  </ul>
</div>

Upvotes: 1

Related Questions