Skip to content Skip to sidebar Skip to footer

Finding Which Element Is Clicked In The Dom

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

Solution 1:

Pure javascript:

<script>document.onclick = function(evt) {
    var evt=window.event || evt; // window.event for IEif (!evt.target) evt.target=evt.srcElement; // extend target property for IEalert(evt.target); // target is clicked
  }
</script>

Solution 2:

event.target sounds like what you're after.

$('#id').click(function(e) {
    //e.target will be the dom element that was clicked on
});

Solution 3:

Update for 2019. IE does not exist anymore, Edge goes chromium and JQuery is falling out of favour.

To determine the clicked element, simply do:

document.onclick = e => {

    console.log(e.target); 
}

Post a Comment for "Finding Which Element Is Clicked In The Dom"