开发者

Select elements whose children don't contain specific elements in jQuery

I want to select all divs on a page whose children don't contain an element with a specific class.

I can select elements whose descendants do contain the class wi开发者_运维技巧th:

$('div').has('.myClass');

So I just want the inverse of this.


I'd use ".filter()":

var theDivs = $('div').filter(function() {
  return $(this).find('.myclass').length === 0;
});


A simple $("div:not(:has(.myClass))") will do the job.

How it works internally in jQuery?

1) $("div") - gets all DIVs from the document.

2) :not(:has(.myClass)) - These are two statements one nested in another. Now jQuery executes :has(.myClass) on resulted DIVs in above step and gets all DIVs with class name 'myClass'

3) :not() - This pseudo-selector method will be applied on All DIVs from Step 1 against the DIVs resulted from second statement to find DIVs without '.myClass'. This is possible by looping through all DIVs from Step 1 and comparing DIVs from second step.


$('div:not(:has(*>.myClass))');


$('div').has(':not(.myClass)');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜