<div class="test">
<div class="example"></div>
</div>
<div class="test">
</div>
如何將jQuery應用於類test
的元素,僅當它不包含子類example
的子元素?如果父元素不包含某個子元素, jQuery
<div class="test">
<div class="example"></div>
</div>
<div class="test">
</div>
如何將jQuery應用於類test
的元素,僅當它不包含子類example
的子元素?如果父元素不包含某個子元素, jQuery
$('.test:not(:has(.example))')
- 或 -
$('.test').not(':has(.example)')
這個人工作得最好,謝謝! – UserIsCorrupt 2012-04-16 09:16:19
你可以使用方法children用 「實例」,並測試它是否是空的
jQuery的:
jQuery.contains(document.documentElement, document.body); // true
jQuery.contains(document.body, document.documentElement); // false
可能
$('.test').filter(function() { return !$(this).children('.example').length; });
此篩選出有任何元素任何匹配.example
的孩子。如果你想根據後代(不只是孩子)過濾,你可以用.find
代替.children
。
$('.test').each(function() {
if(!$(this).children().hasClass("example")){
//your code
}
});
也許這樣嗎?我沒有測試過這...
$(':not(.test:has(.example))').css('color', 'red');
這個問題似乎現成的,你發現所有的.test
的filter
功能對象,然後過濾時只保留其中沒有.example
的對象:
$(".test").filter(function() {
return($(this).find(".example").length == 0);
});
if ($('#yourDiv').children().hasClass("className")) {
// yourDivID' has any children whose class name =>'className'
}
的
可能重複[如何選擇元素不具有特定的子元素使用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