JQuery click () for nested div

The code can probably explain this better than I can:

<div class="wrapper"> <div class="inner1"></div> <div class="inner2"></div> </div> <script> $('div').click(function(){ var class_name = $(this).attr('class'); do_something(class_name); }); </script> 

When I click on div inner1 div, it runs do_something() with inner1 div AND wrapper .

With site building, nested divs will happen a lot. Is there a dynamic way to fix this problem and run only the top level div (in this case inner1 )?

+4
source share
5 answers

Use stopPropagation :

 $('div').click(function(e){ e.stopPropagation(); var class_name = $(this).attr('class'); do_something(class_name); }); 

On the other hand: are you sure that this is what you are trying to do? You might want to change your selector ( $('div') ) only for the target DIV you want.

+19
source

You need to prevent bubbling events. Using jQuery you will do the following:

 $('div').click(function(e) { e.stopPropagation(); // Other Stuff }); 
+2
source

You select the "div", so on every single div that is clicked, it will be launched. This includes wrapper, inner1 and inner2 in this example.

If you want inner1 to disable this feature, you will look like this:

 $('.inner1').click(function(){ var class_name = $(this).attr('class'); do_something(class_name); }); 
0
source
 <div class="wrapper"> <div class="inner1"></div> <div class="inner2"></div> </div> <script> $('div').click(function(ev){ var class_name = $(this).attr('class'); do_something(class_name); ev.stopPropagation(); }); </script> 
0
source

The event bubbles until you stop it using the stopPropagation method:

 $('div').click(function(e){ e.stopPropagation(); var class_name = $(this).attr('class'); do_something(class_name); }); 
0
source

All Articles