let say i want to bind all items that are under
#mainDiv .user
Except
#mainDiv #exception .user
I can think of
$('#mainDiv .user').bind('event',function(){
if($(this).parents('#exception').length>0){}else{
// do stuff;
}
});
or:
$('#mainDiv :not('#exception').find('.user').bind('event',function(){
if($(this).parents('#exception').length>0){}else{
// do stuff;
}
});
Whats a better one?
I might suggest instead something like
$('#mainDiv .user').not('#mainDiv #exception .user').bind('event',function()
{
//do stuff
});
the not() function takes a previously existing jquery set and removes the elements from within it that qualify for the selector that's passed in as a parameter.
filtering the pool up front is cleaner and more performant (probably doesn't matter, but it's good practice) than having both a selector and an if statement, and once you've filtered, the if statement is unnecessary.
as a side note, filtering for "#mainDiv #exception .user" seems kind of odd to me. "#exception" should be a unique identifier all its own - unless you're concerned that for some reason "#mainDiv" might be a child of "#exception".
First get all the elements, then remove the ones that you want to exclude:
$('#mainDiv .user').not('#mainDiv #exception .user').bind('event', function(){
// do stuff
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With