Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Find out which element was clicked without attaching any eventlistener to it?

I am confused on finding an approach to resolve this issue. Consider below html

<body>
  <div id="parent" onclick="myFunc">
     <div id="child-a"></div>
     <div id="child-b"></div>
     <div id="child-c"></div>
     <div id="child-d"></div>
     <div id="child-e"></div>  
  </div>
</body>

Event listener is attached to the parent element. If a user clicks on lets say 'child-c', is there any way to find out using "myFunc" that which div was clicked? In this case 'child-c'. Any possible solution using pure JS or jQuery?

Let me know if more explanation is required. Thank you for helping.

-Nishant

like image 870
nishant limbachiya Avatar asked Aug 20 '11 06:08

nishant limbachiya


3 Answers

Yes, use target:

function(e){
    // e.target is the clicked div
}

Example: http://jsfiddle.net/Paulpro/AfA4t/

like image 172
Paul Avatar answered Oct 15 '22 17:10

Paul


$("#parent").click(function(e){
   console.log(e.target);
});

Demo: http://jsfiddle.net/4bC6K/

like image 4
Dogbert Avatar answered Oct 15 '22 17:10

Dogbert


Yes, you can check the event's target property which will indicate the element that was clicked. You can read more about event properties here.

like image 1
jtbandes Avatar answered Oct 15 '22 19:10

jtbandes