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.
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.
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.
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.
The ("parent > child") selector selects all elements that are a direct child of the specified element.
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))');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With