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