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
Paolo Bergantino Jun 08 '09 at 17:13 2009-06-08 17:13
source share