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

标签 jquery

我正在寻找仅选择器的解决方案,而不是使用 .find() 或其他 jquery 函数的解决方案。

我想知道为什么如果我这样做$('.parentClass:has(".childrenClass")'),如果它们的子元素之一具有.childrenClass,它会返回元素

但是如果我这样做 $('.parentClass:not(".childrenClass")') 它会返回所有元素,即使它们的子元素之一具有 .childrenClass

有没有办法仅在所有子元素都没有特定类的情况下才选择元素?

最佳答案

I wander why if I do $('.parentClass:has(".childrenClass")'), it returns elements if one of their children has .childrenClass but if I do $('.parentClass:not(".childrenClass")') it returns all elements even if one of their children has .childrenClass

因为 :not(".childrenClass"):has(".childrenClass") 并不完全相反。 :not 测试该元素是否与选择器不匹配。 :has 测试该元素的子元素是否与选择器匹配。

Is there a way to select element only if all of their children have not a specific class?

是的,您可以组合 :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>

关于jquery - 如果子元素没有特定的类,则选择一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30647994/

相关文章:

jQuery 鼠标点击事件处理程序

jquery - 更改元素位置后的 CSS 样式

jquery - CSS定位元素

javascript - 如何使用 javascript 获取对象索引值的 JSON 响应

javascript - 使用 javascript 从实时数据更新 json 数组

javascript - 如何在 Materialise CSS 中过滤卡片

php - 处理 Exec_Shell 脚本时显示加载图像

javascript - IE10 上的 Jquery 问题

用于动态 HTML 表格生成的 Javascript 库

javascript - 如何在 Angular JS 中每 5 秒重新加载一次网格?