问题
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.
回答1:
$('.myclass').not('#myid');
http://api.jquery.com/not/
回答2:
Try .not() – it removes any element matching the selector.
回答3:
$('.myclass').not('#myid')
回答4:
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.
回答5:
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.
回答6:
I think you're looking for not()
回答7:
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.
回答8:
You're all wrong. Not is not strictly the opposite of Find because Not only searches the current elements and not the descendents, while Find() will search through descendants to see if a certain criteria matches. The opposite of Find is instead .Not(:has(...)).
来源:https://stackoverflow.com/questions/2717329/opposite-of-find