2012-04-16 161 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' 
} 
相關問題