jQuery click event on parent, but finding the child (clicked) element
Solution 1
You need to pass event object to function to get the item that triggered the event, event.target will give you the source element.
$('#p').bind('click', function(event) {
alert(event.target.id);
});
or
$('#p').bind('click', function(event) {
alert($(event.target).attr('id'));
});
Edit
The first method event.target.id
is preferred over second $(event.target).attr('id')
for performance, simplicity and readability.
Solution 2
You can try the below code. Also try the jsfiddle too(demo).
$('#p').on('click', function(event) {
alert(event.target.id);
});
The answer to your second question is you can assign event to the child and remove from it's parent. Check this out.
.stopPropagation();
Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. Read more
if you want the specific event to be executed only and allow no other event to be fired you use code below
event.stopImmediatePropagation()
Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree. Read more
I hope this will solve your problem. If you have any questions please don't hesitate to ask. Thanks
Solution 3
If your elements have grandchildren, there is a better way to get just the child. Note the greater than sign.
$('.parent > .child').click(function() {
// This will be the child even if grandchild is clicked
console.log($(this));
});
Mahdi
Updated on August 04, 2022Comments
-
Mahdi over 1 year
let say I have a parent element which has so many nested child elements inside of itself:
<div id="p"> <div id="c1"> <div id="c2"></div> <div id="c3"></div> </div id="c4"> <div id="c5"></div> </div> </div>
I've already bind a
click
event on the parent:$('#p').bind('click', function() { alert($(this).attr('id')); });
Because the event is assigned to the parent element, I always see the parent id, however, I'm wondering if there is any possible way to find out which of this child elements has been clicked?
I also can't assign any event to the child elements or remove the event listener from parent div.
-
Mahdi over 11 yearsthanks man, it works! :) ... i should wait to accept your answer!
-
Remy almost 11 yearsFor the record,
$(event.target).attr('id')
is the much slower version ofevent.target.id
- see bit.ly/jqsource and search forSizzle.attr = function
. jQuery (or rather, Sizzle) has to go through all that code to get you your id, where just using the DOM gets it for you directly. -
Anant - Alive to die over 6 yearsuseful for me. +1