简体   繁体   中英

How to get the id of the element that is clicked on the page

I have this situation. I have a JavaScript function that does some work on document click:

$(document).click(function () {
//---Some work is done---
});

But I also want to check which document element is clicked? So, how can I get the clicked element id anywhere in the whole document?

try this

$(document).click(function (e) {
//---Some work is done---
 var id = e.target.id;
});

DEMO

The element from which the event was originated can be referred using the event's target property

$(document).click(function (e) {
    var id = e.target.id
});

Note: this will work only if all elements in your page has an id attribute.

Another approach could be to find the closest element with has an id like

$(document).click(function (e) {
    var id = $(e.target).closest('[id]').attr('id');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM