Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery click event on parent, but finding the child (clicked) element

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.

like image 953
Mahdi Avatar asked Oct 06 '12 09:10

Mahdi


People also ask

Can we get the children element from the parent element using jQuery?

jQuery children() method is used to get the direct children of the selected HTML element. You can use children() method to traverse through the child elements of the selected parent element.

What is the use of parent () and child () method in jQuery?

It is a jQuery Selector used to select all elements that are the direct child of its parent element. Parameter Values: parent: Using this, the parent element will be selected. child: Using this, the direct child element of the specified parent element will be selected.

How do you check if an element is a child of a parent in JavaScript?

To check if an element is a child of a parent with JavaScript, we can use the parent element's contains method. const contains = (parent, child) => { return parent !== child && parent. contains(child); };


1 Answers

You need to pass event object to function to get the item that triggered the event, event.target will give you the source element.

Live Demo

 $('#p').bind('click', function(event) {     alert(event.target.id);  }); 

or

Live Demo

$('#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.

like image 84
Adil Avatar answered Oct 05 '22 13:10

Adil