Javascript 如何选择不包含某个子元素的元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10168248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:08:52  来源:igfitidea点击:

How can I select an element which does not contain a certain child element?

javascriptjquery

提问by UserIsCorrupt

<div class="test">
 <div class="example"></div>
</div>

<div class="test">
</div>

How can I apply jQuery to an element with the class testonly if it doesn't contain a child element with the class example?

test仅当它不包含具有类的子元素时,如何将 jQuery 应用于具有类的元素example

回答by vol7ron

$('.test:not(:has(.example))')

-or-

-或者-

$('.test').not(':has(.example)')

回答by Jon

Possibly

可能

$('.test').filter(function() { return !$(this).children('.example').length; });

This filters out any elements that have any child that matches .example. If you want to filter based on descendants (not just children) that you can substitute .findfor .children.

这会过滤掉任何具有匹配 的子元素的元素.example。如果你想过滤器基于后代(不只是孩子),您可以替代.find.children

回答by Andreas Wong

$(':not(.test:has(.example))').css('color', 'red');????????????????????????????????????

http://jsfiddle.net/9fkz7y1g/

http://jsfiddle.net/9fkz7y1g/

回答by Marc

jQuery contains():

jQuery contains()

jQuery.contains(document.documentElement, document.body); // true
jQuery.contains(document.body, document.documentElement); // false

回答by jfriend00

This problem seems ready-made for the filterfunction where you find all the .testobjects and then when filtering retain only the ones that don't have .examplein them:

这个问题似乎是为filter找到所有.test对象然后过滤时只保留其中没有的函数的现成问题.example

$(".test").filter(function() {
    return($(this).find(".example").length == 0);
});

回答by hjuster

 $('.test').each(function() {
    if(!$(this).children().hasClass("example")){
       //your code
    }
}); 

Maybe like this? I haven't tested this...

也许像这样?我没有测试过这个...

回答by Andrés

You could use the method childrenwith ".example" and test if it is empty

您可以使用带有“.example”的方法children并测试它是否为空

回答by Shekhar Kadam

if (!$('#yourDiv').children().hasClass("className")) {
    //i.e. yourDivID' has no any children whose class name =>'className'
}