如何从所有元素jQuery中删除类


82

我正在使用以下内容更改元素的类

  $("#"+data.id).addClass("highlight")

给出以下列表。

 <div id="menuItems"> 
 <ul id="contentLeft" class="edgetoedge"> 
 <li  class="sep" ">Shakes and Floats</li> 
 <li id="297"><a href="#" onClick="cart('297','add')"><small>$5.00</small><b>Vanilla</b>     </a></li> 
 <li id="298"><a href="#" onClick="cart('298','add')"><small>$5.00</small><b>Peanut Butter</b></a></li> 
 <li id="299"><a href="#" onClick="cart('299','add')"><small>$5.00</small><b>Combo</b></a></li> 
 <li id="300"><a href="#" onClick="cart('300','add')"><small>$5.00</small><b>Chocolate</b></a></li> 
 <li id="301"><a href="#" onClick="cart('301','add')"><small>$5.00</small><b>Strawberry</b></a></li> 
 <li id="303"><a href="#" onClick="cart('303','add')"><small>$5.00</small><b>Banana</b></a></li> 
 <li id="304"><a href="#" onClick="cart('304','add')"><small>$5.00</small><b>Root Beer Float</b></a></li> 
 <li id="305"><a href="#" onClick="cart('305','add')"><small>$5.00</small><b>Espresso</b></a></li> 
 </ul>
 </div> 

我以为我可以用这个删除课程...

  $(".edgetoedge").removeClass("highlight");

但这是行不通的。如何删除课程?

Answers:


158

您需要选择该类中li包含的标签.edgetoedge.edgetoedge仅匹配一个ul标签:

$(".edgetoedge li").removeClass("highlight");

38

尝试:$(".highlight").removeClass("highlight");。通过选择,$(".edgetoedge")您仅在该级别上运行功能。


您的答案应该被接受。一个非常有趣的技巧,您可以节省我的时间。
vietnguyen09 '18

18

这只会从具有highlight该类的所有内容中删除edgetoedge该类:

$(".edgetoedge").removeClass("highlight");

我想你想要这个:

$(".edgetoedge .highlight").removeClass("highlight");

.edgetoedge .highlight选择会选择一切,是的东西与孩子edgetoedge阶级和有highlight阶级。


2
+1可以在不知道元素类型的情况下定位项目。
安迪



0

从所有元素中删除jquery中的类的最佳方法是通过元素标签定位。例如,

$("div").removeClass("highlight");
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.