Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 206
pelms Avatar asked Feb 24 '11 16:02

pelms


People also ask

Which jQuery content filter would you use to select elements that contain certain child elements?

nth-of-type() Selector: This selector is used to select all elements that are the nth-child of their parent in relation to siblings with the same element name. only-child Selector: This selector is used to select all elements that are the only child of their parent.

How would you find a child element with a specific class using jQuery?

Given a jQuery object that represents a set of DOM elements, the . children() method allows us to search through the children of these elements in the DOM tree and construct a new jQuery object from the matching elements.

How do you select all child elements except first?

By using the :not(:first-child) selector, you remove that problem. You can use this selector on every HTML element. Another common use case is if you use an unordered list <ul> for your menu.

Which will select all direct child elements in jQuery?

The ("parent > child") selector selects all elements that are a direct child of the specified element.


3 Answers

I'd use ".filter()":

var theDivs = $('div').filter(function() {
  return $(this).find('.myclass').length === 0;
});
like image 97
Pointy Avatar answered Oct 17 '22 16:10

Pointy


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.

like image 44
Epuri Avatar answered Oct 17 '22 17:10

Epuri


$('div:not(:has(*>.myClass))');
like image 3
Homer Avatar answered Oct 17 '22 17:10

Homer