最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Finding which element is clicked in the DOM - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question edited Jun 13, 2010 at 7:57 Bhupi asked Jun 13, 2010 at 7:39 BhupiBhupi 2,9696 gold badges35 silver badges51 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 10

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>

event.target sounds like what you're after.

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

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); 
}
发布评论

评论列表(0)

  1. 暂无评论