简体   繁体   中英

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 with:

$('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)');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM