2012-04-16 196 views
15
<div class="test"> 
<div class="example"></div> 
</div> 

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

如何将jQuery应用于类test的元素,仅当它不包含子类example的子元素?如果父元素不包含某个子元素, jQuery

+0

可能重复[如何选择元素不具有特定的子元素使用jQuery(http://stackoverflow.com/questions/7258606/how-to-select-elements-which-do -not-have-a-specific-child-element-with-jquery) – Jeroen 2015-07-02 06:26:53

回答

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

- 或 -

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

这个人工作得最好,谢谢! – UserIsCorrupt 2012-04-16 09:16:19

1

你可以使用方法children用 “实例”,并测试它是否是空的

1

jQuery的:

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

可能

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

此筛选出有任何元素任何匹配.example的孩子。如果你想根据后代(不只是孩子)过滤,你可以用.find代替.children

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

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

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

http://jsfiddle.net/DZZUZ/2/

2

这个问题似乎现成的,你发现所有的.testfilter功能对象,然后过滤时只保留其中没有.example的对象:

$(".test").filter(function() { 
    return($(this).find(".example").length == 0); 
}); 
-1
if ($('#yourDiv').children().hasClass("className")) { 
    // yourDivID' has any children whose class name =>'className' 
} 
相关问题