views:

122

answers:

7

Is there an opposite of .find()?

Where $('.myclass').except('#myid');

Would grab all elements with .myclass except the element with #myid. I know I could do $('.myclass[id=myid]') in this example, but seems like it would be helpful in other cases.

Thanks

EDIT:

Thanks for the responses! Looks like I just missed seeing .not() and :not() in the documentation.

+4  A: 
josh3736
Thank You! I must have missed that in the jQuery documentation. =/
path411
+1  A: 

Generic

$('selector:not(selector)').doStuff()

Specific

$('.myclass:not(#myid)').doStuff() 

I believe is the correct solution.

Visit http://api.jquery.com/not-selector/

For more use cases and examples.

Owen Allen
+9  A: 
$('.myclass').not('#myid');

http://api.jquery.com/not/

MiffTheFox
+3  A: 

$('.myclass').not('#myid')

vittore
+1  A: 

I think you're looking for not()

+1  A: 

If you want a single string selector, then use this:

$('.myClass:not(#myid)')

This uses the :not() pseudo-class selector instead of the .not() filter function.

It seems counter-intuitive, but this single selector method may be slower at times, because getting elements via class (without filtering) is optimized, it filters each of those as the selector passes in this case.

The alternative, using .not() can be faster, depending on the number of elements matching .myclass, because finding an element by ID is a very fast operation, so excluding it from the set is rather quick.

Nick Craver
+1 for performance notes.
jholster
A: 

Yes there are. You can use either jQuery's :not selector or .not() function. Sample code:

$('.something').not('.else')
$('.something:not(.not-me):not(.neither-me)')

As a side note, CSS3 has native :not pseudo-class.

jholster