4

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?

Toni Michel Caubet
  • 19,333
  • 56
  • 202
  • 378

3 Answers3

15

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

Ben Barden
  • 2,001
  • 2
  • 20
  • 28
2

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
});
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

I would delegate the event:

$( '#mainDiv' ).on( 'event', '.user', function () {

    if ( $( this ).parent().is( '#exception' ) ) { return; }

    // do your thing

});

You could also make a this.parentNode.id === 'exception' check...

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • but that would be same selection than mi first option but with just a different triggering... no? – Toni Michel Caubet Mar 02 '12 at 22:37
  • @ToniMichelCaubet I delegate the event, which is better than binding the handler to all elements... – Šime Vidas Mar 02 '12 at 22:43
  • @ŠimeVidas: That depends. It's not always better, as delegate has more runtime overhead than a simple bind. – Guffa Mar 03 '12 at 08:04
  • @Guffa I meant better as in more proper. When you have multiple elements of the same class that share the same event handler, it is more proper to bind the handler *once* on the parent/ancestor then to bind it on each element individually. – Šime Vidas Mar 03 '12 at 13:35