The jquery click event on the selector returns the child as the target

Today I am starting to lose my mind with Jquery, I am looking at other questions, but so far nothing is working. I have a simple html structure (dynamically added to a for loop).

<div id="cell'+i+'" class="cell emptyCell"> <div class="handle"></div> <div class="content"></div> </div> 

I use the "on" method to bind the "click event" of the elements of the .emptyCell class with a custom function.

 $(document).on('click','.emptyCell', function(e){ console.log(e.target.id); }); 

But when the user clicks on the .content div (child of emptyCell), he catches this event, and the console prints "undefined", since the .content elements do not have identifiers here.

How is this possible? Shouldn't the .on function only bind the elements of the .emptyCell class?

thanks for the help

+7
javascript jquery html
source share
1 answer

e.target refers to the actual element where the click occurred (these may be handle or content elements), if you want to pass emptyCell , then you can use this or e.currentTarget

 $(document).on('click','.emptyCell', function(e){ console.log(this.id); console.log(e.currentTarget.id); }); 

Demo: Fiddle

+21
source share

All Articles