Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Selectors - where item does not have children with a certain class

I want to select list items that are immediate children of #nav, that do not themselves have immediate children with an 'active' class.

This is what I think it should be but it does not work:

$('#nav > li:not(> a.active)')
like image 937
Trevor Avatar asked Apr 21 '10 14:04

Trevor


People also ask

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.

What is the class used to select an element which has no child?

The :empty CSS pseudo-class represents any element that has no children.

Is it possible to select an element if it contains a specific child element?

Is it possible to select an element if it contains a specific child element? Unfortunately not yet. The CSS2 and CSS3 selector specifications do not allow for any sort of parent selection.

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.


3 Answers

I really like Ken's solution, but just for an alternative take.

You could add the active class to your list items instead of your links inside. Then your selector could look like:

$("ul#nav li:not(.active)");

If you want to style the links based on the active class, your CSS could look like this:

#nav li.active a{background-color:red;}
like image 136
Jon Avatar answered Oct 11 '22 15:10

Jon


This is how you do it:

    $('#nav > li:not(:has(a.active))')
like image 21
regisbsb Avatar answered Oct 11 '22 13:10

regisbsb


You'll need to use jQuery's filter function:

$('#nav > li').filter(function() { return !($(this).children().is('.active')); })
like image 39
Ken Browning Avatar answered Oct 11 '22 13:10

Ken Browning