Best way to add exceptions in jquery select path

let's say I want to link all the elements under

#mainDiv .user 

Besides

 #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; } }); 

What's better?

+4
source share
3 answers

I could suggest instead something like

 $('#mainDiv .user').not('#mainDiv #exception .user').bind('event',function() { //do stuff }); 

the not () function takes a pre-existing jquery set and removes elements from it that qualify for the selector, which is passed as a parameter.

Filtering the pool on the front panel is cleaner and more efficient (probably it doesnโ€™t matter, but itโ€™s good practice) than having both a selector and an if statement, and after you filter out the if statement is not needed.

as a side note, filtering for "#mainDiv # exception.user" seems strange to me. "#exception" should be the only unique identifier - unless you are worried that for some reason "#mainDiv" might be a child of "#exception".

+14
source

First get all the elements, then delete the ones you want to exclude:

 $('#mainDiv .user').not('#mainDiv #exception .user').bind('event', function(){ // do stuff }); 
+2
source

I would delegate the event:

 $( '#mainDiv' ).on( 'event', '.user', function () { if ( $( this ).parent().is( '#exception' ) ) { return; } // do your thing }); 

You can also check this.parentNode.id === 'exception' ...

0
source

Source: https://habr.com/ru/post/1399472/


All Articles