views:

46

answers:

2

The question was asked to me in an interview.

How to find which element is clicked by the user in the DOM using JQuery or Javascript or Both?

NOTE: User can click on any element in the DOM whether it is an img, div or even span.

If you can suggest some example then it will be very much helpful.

Thanks in advance

+2  A: 

event.target sounds like what you're after.

$('#id').click(function(e) {
    //e.target will be the dom element that was clicked on
});
Dan F
I replaced '#id' with document and it is working the way I wanted. thnx
Bhupi
+3  A: 

Pure javascript:

<script> 
  document.onclick = function(evt) {
    var evt=window.event || evt; // window.event for IE
    if (!evt.target) evt.target=evt.srcElement; // extend target property for IE
    alert(evt.target); // target is clicked
  }
</script>
Sergei
Thanks a lot, now I found both JQuery and Javascript ways :)
Bhupi