28

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,799
  • 66
  • 75
  • 101
Bluefire
  • 13,519
  • 24
  • 74
  • 118

5 Answers5

49

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
  • 146,340
  • 25
  • 209
  • 204
21

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,819
  • 3
  • 33
  • 60
Wafae Mks
  • 219
  • 2
  • 2
6
$('body').on('click', function(e){
    var id = $(this).attr('id');
    alert(id);
});
imkost
  • 8,033
  • 7
  • 29
  • 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
3

try this

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

    var id = $(this).attr('id');
    console.log(id); 
});
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
  • 74,255
  • 12
  • 74
  • 103