简体   繁体   English

查找没有直属子类的元素

[英]Find element that has no direct children with specific class

In a page of HTML elements, I am trying to find a parent element with class .dmc that does not contain a direct child element with a specific class .dynamic , using JQuery. 在HTML元素页面中,我尝试使用JQuery查找类.dmc的父元素,该父元素不包含具有特定类.dynamic的直接子元素。

I have tried: 我努力了:

$('.dmc:not(:has(.dynamic))')

However this checks all descendants, and I only want to check the first level of descendants. 但是,这将检查所有后代,而我只想检查后代的第一级。

I think there is a very simple answer, but I can't quite come up with it. 我认为有一个非常简单的答案,但我不太想出来。 Any help appreciated! 任何帮助表示赞赏!

Since :has is already jQuery-specific, you could use an unrooted > , which jQuery's Sizzle selector engine seems to support: 由于:has是jQuery特有的,因此您可以使用一个无根的> ,jQuery的Sizzle选择器引擎似乎支持:

$(".dmc:not(:has(> .dynamic))").addClass("green");
// --------------^

 $(".dmc:not(:has(> .dynamic))").addClass("green"); 
 .green { color: green; font-weight: bold; } 
 <div class="dmc">1</div> <div class="dmc">2 <div class="dynamic">dynamic</div> </div> <div class="dmc">3</div> <div class="dmc">4 <div class="dynamic">dynamic</div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 

But I'd be slightly worried about it, and would probably go for filter instead: 我对此会有些担心,并且可能会选择filter

$(".dmc").filter(function() {
  return $(this).children(".dynamic").length == 0;
}).addClass("green");

 $(".dmc").filter(function() { return $(this).children(".dynamic").length == 0; }).addClass("green"); 
 .green { color: green; font-weight: bold; } 
 <div class="dmc">1</div> <div class="dmc">2 <div class="dynamic">dynamic</div> </div> <div class="dmc">3</div> <div class="dmc">4 <div class="dynamic">dynamic</div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM