Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What JQuery selector excludes items with a parent that matches a given selector?

I have

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

as a way to select all the elements whose classes are either foo or bar and who do not descend from an element whose class is baz. Is there a selector that will accomplish the same thing without the need for a filtering lambda?

<div class='foo'/><!--match this--> <div class='bar'/><!--match this--> <div class='baz'>     <div class='foo'/> <!--don't match this--> </div> 
like image 777
Dan Davies Brackett Avatar asked Jun 08 '09 16:06

Dan Davies Brackett


People also ask

What is the use of parent () and child () method in jQuery?

It is a jQuery Selector used to select all elements that are the direct child of its parent element. Parameter Values: parent: Using this, the parent element will be selected. child: Using this, the direct child element of the specified parent element will be selected.

What does parent () do in jQuery?

The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.

What is a parent child selector?

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

Which is the jQuery selector function used for selecting the elements?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.


1 Answers

The truth of the matter is that jQuery simply does not have a particularly elegant way to do what you want. While chaos' answer does work, you have to wonder whether the complicated selector (that would be about as slow as a selector can be in a complicated webpage) is worth it over the more verbose but faster filter function you have. This is not really that big of a deal, I am just personally weary of particularly long, convoluted selectors when I can avoid it.

A different option is to create your own selector, since 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 selector engine and documentation can be found here: Sizzle Custom Pseudo-Selectors

like image 135
Paolo Bergantino Avatar answered Oct 19 '22 03:10

Paolo Bergantino