26

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?

TylerH
  • 20,816
  • 57
  • 73
  • 92
Bluefire
  • 12,429
  • 22
  • 67
  • 111

5 Answers5

47

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.

Adil
  • 143,427
  • 25
  • 201
  • 198
17

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.

CODE-REaD
  • 2,513
  • 3
  • 27
  • 56
Wafae Mks
  • 179
  • 1
  • 2
5
$('body').on('click', function(e){
    var id = $(this).attr('id');
    alert(id);
});
imkost
  • 7,803
  • 6
  • 28
  • 47
  • 2
    Note that the OP was asking about `e.target`, which isn't necessarily the same as `this` - especially not if the click handler is bound to the body. – nnnnnn Jan 20 '13 at 08:48
  • True, although my aim was to find a way to get the id of an element from within an event; e.target was just a suggestion. – Bluefire Jan 20 '13 at 08:49
  • 1
    Well if `this` is the right element just say `this.id`, you don't need to create a jQuery object and call the `.attr()` function. – nnnnnn Jan 20 '13 at 08:51
  • @nnnnnn, wow. Working with jQuery absolutly forgot about native js. `this.id` is much easier to use, of course – imkost Jan 20 '13 at 08:56
  • 1
    `this` doesn't seem to work for me; `$(this).attr('id');` returns `undefined` and `this.id` doesn't return anything. – Bluefire Jan 20 '13 at 08:57
  • 1
    I suspect the problem is as per my original comment: 'this' is the body element because that's what the click handler was attached to, and the body doesn't have an id specified... – nnnnnn Jan 20 '13 at 11:27
2

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>`
});
Jai
  • 72,925
  • 12
  • 73
  • 99
2

try this

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

    var id = $(this).attr('id');
    console.log(id); 
});