Let’s says I have the following code :
<div class="body">
Click me and it will work.
<div class="head">Click me and nothing will happen.</div>
</div>
I want to display the “it works” when you click inside the .body div but not inside the .head div. How can I do this?
With this code, the log appears even if you click on head:
<script>
$('.body').click(function(){console.log('it works !');});
</script>
Event bubbling is causing your troubles. Essentially, the event handler for your ‘head’ class would capture the click and then bubble that event up to your ‘body’ handler because there are nested.
Here is an excellent primer on event bubbling, how it works, and how to control event bubbling.
Here is working jsFiddle example for you to test.