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
How can I select an element which does not contain a certain child element?
提问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 test
only 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 .find
for .children
.
这会过滤掉任何具有匹配 的子元素的元素.example
。如果你想过滤器基于后代(不只是孩子),您可以替代.find
的.children
。
回答by Andreas Wong
$(':not(.test:has(.example))').css('color', 'red');????????????????????????????????????
回答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 filter
function where you find all the .test
objects and then when filtering retain only the ones that don't have .example
in 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
回答by Shekhar Kadam
if (!$('#yourDiv').children().hasClass("className")) {
//i.e. yourDivID' has no any children whose class name =>'className'
}