Reputation: 408
how can i get target clicked element even if this element inside other elements with same type like (div)
i have 3 divs inside each others , when i declare click events for div and i clicked top div i got 3 click events for the parents too.
so i want just one click events for the target element i clicked and ignore the others
My Try
jQuery('div').click(function(e) {
var clicked = jQuery(e.target);
// Ensure we're checking which list item is clicked,
// other children should be allowed
if(clicked.parents().length > 0) {
// :first ensures we do not select higher level list items
alert($(clicked).html());
return ;
}
else
{
alert($(clicked).html());
}
});
Upvotes: 2
Views: 4239
Reputation: 237845
Doing stopPropagation
is one method. Rather nicer, I think, is to check if the current element is the same as the event target, which means you can still handle events with handlers higher up the tree:
jQuery('div').click(function(e) {
if (this === e.target) {
// we're handling on the clicked element
}
}
Upvotes: 1
Reputation: 25029
You need to stop the click event propagating up the DOM tree.
http://api.jquery.com/event.stopPropagation/
Upvotes: 0
Reputation: 4632
Your could try adding e.stopPropagation()
inside your click event handler. This will allow the event to trigger on whichever div was clicked, but stop the event from going any further up the dom.
Upvotes: 3