jQuery - 如果子元素没有特定的类,则选择元素

4
我正在寻找一个只使用选择器的解决方案,而不是使用 .find() 或其他 jQuery 函数的解决方案。
我想知道为什么当我执行 $('.parentClass:has(".childrenClass")') 时,如果其中一个子元素拥有 .childrenClass 类,则返回该元素。
但是,如果我执行 $('.parentClass:not(".childrenClass")'),它会返回所有元素,即使其中一个子元素拥有 .childrenClass 类。
是否有一种方法只选择那些其所有子元素都没有特定类的元素?
1个回答

9
我不明白为什么使用 $('.parentClass:has(".childrenClass")') 时,如果其中一个子元素具有 .childrenClass,则返回元素,但如果使用 $('.parentClass:not(".childrenClass")'),则无论其中一个子元素是否具有 .childrenClass,它都会返回所有元素。
因为 :not(".childrenClass") 完全不是 :has(".childrenClass") 的相反。:not 检查该元素是否与选择器不匹配。:has 检查该元素的子元素是否与选择器匹配。
您可以组合 :not 和 :has 以仅选择具有特定类别的所有子元素:

$(".parentClass:not(:has(.childrenClass))").css("background-color", "yellow");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="parentClass">
  Should match, no children with childrenClass
</div>
<div class="parentClass">
  Should match,
  <span>no children with childrenClass</span>
</div>
<div class="parentClass">
  Shouldn't match,
  <span class="childrenClass">has children with childrenClass</span>
</div>
<div class="parentClass">
  Shouldn't match,
  <span class="childrenClass">has children</span>
  <span class="childrenClass">with childrenClass</span>
</div>

我必须承认,这真的让我很惊讶,因为:has在历史上并不友好。之前,我认为你必须使用filter:

$(".parentClass").filter(function() {
  return $(this).find(".childrenClass").length == 0;
}).css("background-color", "yellow");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="parentClass">
  Should match, no children with childrenClass
</div>
<div class="parentClass">
  Should match,
  <span>no children with childrenClass</span>
</div>
<div class="parentClass">
  Shouldn't match,
  <span class="childrenClass">has children with childrenClass</span>
</div>
<div class="parentClass">
  Shouldn't match,
  <span class="childrenClass">has children</span>
  <span class="childrenClass">with childrenClass</span>
</div>


1
能否在单个选择器中完成这个操作? - Below the Radar
@BelowtheRadar:令我非常惊讶的是,:not:has 可以一起使用,可以查看更新后的答案。 - T.J. Crowder
这正是我正在寻找的!真令人惊讶! - Below the Radar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接