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?
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.
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.
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.
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.
$('body').on('click', function(e){
var id = $(this).attr('id');
alert(id);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With