Bluefire Bluefire - 7 months ago 31
HTML Question

How to get an element's ID from event.target

Consider a piece of code that looks like the following:

$('body').on('click', function(e){

});


I know there is a way to get the element type from
e.target
, i.e.
e.target.nodeName
, but how can I get the id of that element from that? If that can't be done, is there another way to get the id of the element that was clicked on?

Answer

You can use e.target.id. e.target represents DOM object and you can access all its property and methods.

$('body').on('click', function(e){
    alert(e.target.id);    
});

You can convert the DOM object to jQuery object using jQuery function jQuery(e.target) or $(e.target) to call the jQuery functions on it.