Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 726
Bluefire Avatar asked Jan 20 '13 08:01

Bluefire


People also ask

Is event target an element?

Definition and Usage. The target event property returns the element that triggered the event. The target property gets the element on which the event originally occurred, opposed to the currentTarget property, which always refers to the element whose event listener triggered the event.

Which element is event target in the event object?

When an event is fired, the element that fires the event is known as the emitter. This element is what we call the target. So, the target property of that event object refers to the event emitter.


3 Answers

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.

like image 51
Adil Avatar answered Oct 23 '22 12:10

Adil


To get the attribute of a target element in JavaScript you would simply use:

e.target.getAttribute('id');

See also: https://stackoverflow.com/a/10280487/5025060 for the subtle distinction between DOM properties and their attributes.

like image 21
Wafae Mks Avatar answered Oct 23 '22 12:10

Wafae Mks


$('body').on('click', function(e){
    var id = $(this).attr('id');
    alert(id);
});
like image 5
imkost Avatar answered Oct 23 '22 11:10

imkost