[英]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; 我想从子代号2的
<a>
之外的所有锚点中删除.active
类; 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. 感谢大家。
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)
。
$("#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>
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; 您原来的选择器正在寻找
<li>
元素,该元素不是其父元素的第二个子元素,而且也不是<a>
元素; this is true for all <li>
elements. 所有
<li>
元素都是如此。
/*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>
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.