pelms
pelms

Reputation: 1242

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.

Upvotes: 14

Views: 7314

Answers (4)

Epuri
Epuri

Reputation: 300

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.

Upvotes: 5

Homer
Homer

Reputation: 7826

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

Upvotes: 3

Pointy
Pointy

Reputation: 414086

I'd use ".filter()":

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

Upvotes: 12

Richard Dalton
Richard Dalton

Reputation: 35803

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

Upvotes: 1

Related Questions