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
Solution 1:
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.
Solution 2:
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.
Solution 3:
$('body').on('click', function(e){
var id = $(this).attr('id');
alert(id);
});
Solution 4:
This can be done:
$('body').on('click', 'a', function (e) {//you can do $(document) instead $(body)
e.preventDefault();
alert($(this).attr('id'));//<--this will find you the each id of `<a>`
});
Post a Comment for "How To Get An Element's Id From Event.target"