Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to add exceptions in jquery selectors paths

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?

like image 301
Toni Michel Caubet Avatar asked Dec 04 '22 04:12

Toni Michel Caubet


2 Answers

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".

like image 164
Ben Barden Avatar answered Dec 17 '22 08:12

Ben Barden


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
});
like image 31
Guffa Avatar answered Dec 17 '22 09:12

Guffa