Which jQuery selector excludes items with a parent that matches the given selector?

I have

var $set = $('.foo,.bar').filter( function() {return $(this).parents('.baz').length < 1;}); 

as a way to select all elements whose classes are either foo or bar , and which do not go down from an element whose class is baz . Is there a selector that will do the same thing without having to filter lambda?

 <div class='foo'/><!--match this--> <div class='bar'/><!--match this--> <div class='baz'> <div class='foo'/> <!--don't match this--> </div> 
+65
jquery jquery-selectors css-selectors
Jun 08 '09 at 16:39
source share
7 answers

The truth is that jQuery just doesn't have a particularly elegant way to do what you want. While the chaos answer works, you need to wonder if the complex selector (which will be about as slow as the selector on a complex web page) is worth the fact that you have a more verbose but faster filtering function. This is actually not a very big deal, I'm just tired of the particularly long, confusing selectors when I can avoid this.

Another option is to create your own selector, as jQuery is awesome:

 jQuery.expr[':'].parents = function(a,i,m){ return jQuery(a).parents(m[3]).length < 1; }; $('.foo,.bar').filter(':parents(.baz)'); 

The expr map is part of the Sizzle selection engine, and the documentation can be found here: Sizzle Custom Pseudo-Selectors

+73
Jun 08 '09 at 17:13
source share
 $('.foo:not(.baz .foo),.bar:not(.baz .bar)') 
+29
Jun 08 '09 at 16:44
source share

I could not get this to work:

 $(".children:not(#parent .children)"); 

But I can make this work:

 $(".children").not($("#parent .children")); 

Note. Not sure if this has anything to do with jQuery version, I am using 1.2.6

+16
Sep 28 '09 at 5:12
source share

Try this:

 $('div').filter(function () { return ($(this).parent().not('.baz')); }) 
+3
Apr 02 '13 at
source share

The chaos selector gives the job:

 $('.foo:not(.baz .foo),.bar:not(.baz .bar)') 

I just wanted to give you advice on a FireBug extension called FireFinder , which you can use to test css / jquery selectors.

From the Web site: Firefinder is a Firebug extension (in Firefox) and offers functionality to quickly find HTML elements matching selected CSS selectors or XPath expressions. This allows you to instantly test your CSS selectors on the page while viewing the content, and the relevant elements will be highlighted.

+1
Jun 08 '09 at 16:59
source share

var $li = jQuery('li', this).not('.dropdown-menu > li');

I use the Roots theme and they change the drop-down lists from the "submenu" to ".dropdown-menu"

+1
Aug 24 '12 at 20:19
source share

Add a: not ('. Baz') to your top level selector.

0
Jun 08 '09 at 16:44
source share



All Articles