如果父元素不包含某个子元素; jQuery的
如果jQuery不包含带有类example
的子元素,我怎样才能将jQuery应用于带有类test
元素?
$('.test:not(:has(.example))')
-要么-
$('.test').not(':has(.example)')
或者
$('.test').filter(function() { return !$(this).children('.example').length; });
这会过滤掉任何与.example
相匹配的子元素。 如果你想根据后代(不仅仅是孩子)进行过滤,你可以用.find
代替.find
。
$(':not(.test:has(.example))').css('color', 'red');
这个问题似乎已经为filter
函数做好了准备,你可以找到所有.test
对象,然后当过滤只保留那些没有.example
的filter
时:
$(".test").filter(function() { return($(this).find(".example").length == 0); });
你可以使用带有“.example”的子方法,并测试它是否为空
jQuery contains()
:
jQuery.contains(document.documentElement, document.body); // true jQuery.contains(document.body, document.documentElement); // false
$('.test').each(function() { if(!$(this).children().hasClass("example")){ //your code } });
也许是这样的? 我没有测试过这个……
if (!$('#yourDiv').children().hasClass("className")) { //ie yourDivID' has no any children whose class name =>'className' }