1091

Is there any way to get the ID of the element that fires an event?

I'm thinking something like:

$(document).ready(function() {
  $("a").click(function() {
    var test = caller.id;
    alert(test.val());
  });
});
<script type="text/javascript" src="starterkit/jquery.js"></script>

<form class="item" id="aaa">
  <input class="title"></input>
</form>
<form class="item" id="bbb">
  <input class="title"></input>
</form>

Except of course that the var test should contain the id "aaa", if the event is fired from the first form, and "bbb", if the event is fired from the second form.

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
Joda
  • 12,796
  • 10
  • 34
  • 33
  • 26
    Your example is a bit odd. You're attaching a click event to 'a', but don't have any anchors. Changing it to $('input.title').click(...) would be a little clearer for future readers of your question. – Jason Moore Nov 12 '08 at 20:43
  • 3
    You can use `event.target.id` in event handler to get id of element that fired an event. – Ilyas karim Oct 05 '17 at 11:32
  • You can take `event` as an *argument in you click callback function* and then use `event.target.id` – Supratim Samantray Sep 04 '20 at 19:40

24 Answers24

1407

In jQuery event.target always refers to the element that triggered the event, where event is the parameter passed to the function. http://api.jquery.com/category/events/event-object/

$(document).ready(function() {
    $("a").click(function(event) {
        alert(event.target.id);
    });
});

Note also that this will also work, but that it is not a jQuery object, so if you wish to use a jQuery function on it then you must refer to it as $(this), e.g.:

$(document).ready(function() {
    $("a").click(function(event) {
        // this.append wouldn't work
        $(this).append(" Clicked");
    });
});
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
samjudson
  • 56,243
  • 7
  • 59
  • 69
  • 13
    Wow! Thanks. Didn't realize that jQuery abstracted that so well. You rock! I would think it would still have the difference between (this) and (event.target) -- being object you bound the event to vs. the object that received the event. – Hafthor Sep 08 '08 at 17:12
  • 18
    Unfortunately, event.target doesn't permit access to its custom attributes. To do that, one must use $(this).attr("organization:thingy");. – Zian Choy Sep 08 '09 at 07:00
  • 17
    @ZianChoy - I'm not quite sure what you mean by "custom attributes", but you can use `$(event.target)` if you need a jQuery method, e.g., `$(event.target).attr("organisation:thingy");`. – nnnnnn Jun 25 '12 at 11:05
  • 3
    I think its of note that if you need access to the event target for manipulating the dom you can do something like this: $(event.target).eq(0). You can then use any method you'd normally use with a dom element like $(event.target).eq(0).find('li') for example. – Rooster Jan 23 '13 at 19:08
  • 37
    Please note, that: event.target is the _real_ item being clicked. If you, for example, you bind a click event to a div, and, inside that div is a P and an H2 element - event.target will return the H2 element or the P, if clicked one of those. "this" will really return the div on which you hung the event, regardless of what child element you clicked. – Rob May 29 '14 at 21:03
  • 4
    I use event.currentTarget.id , event.target.id could also be a child element – radtek Oct 18 '14 at 16:27
  • Sometimes the event was triggered by a not obvious element then you can try to use this `var target = e.originalEvent.explicitOriginalTarget || e.currentTarget[e.currentTarget.length - 1] || e.target;` – powtac Jan 06 '16 at 17:04
  • 1
    Please note, as already mentioned by @RobQuist above the `e.target` is actually the element **on which** the event was occured and it might not always be the element that **triggered** the event. So, the author might need to change the sentence *In jQuery event.target always refers to the element that triggered the event, where 'event'* as there might be cases where it is wrong. BTW, in all cases `e.currentTarget` refers to the element the event handler has been attached to. Please read this: https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget – kabirbaidhya May 13 '16 at 11:12
  • A warning to those using ES6. Arrow functions do not set 'this'. So, basically don't use an arrow function here. – thomas-peter Aug 01 '16 at 03:16
  • @tomwrong: Well, unless you use `event.target` or `event.currentTarget` instead, so you can use `this` for something else. Then an arrow function makes perfect sense. – T.J. Crowder Sep 26 '16 at 08:13
  • After crazy hours of trying and trying I found that if you use `$(document).bind('click','myelement,function(event){...}')` then `$(this)` will return `document` not `myelement`. – Ahmad Maleki Nov 09 '16 at 06:32
  • Apparently this solution does not work for radio buttons and dropdowns. – Chiwda Sep 08 '17 at 16:00
  • No, `this` does not always work, sometimes it is undefined depending on the context; just another reason JavaScript has lost its way. – Coder Guy Apr 20 '20 at 17:10
  • Thanks this worked for me. Apparently, "When you perform an DOM query through jQuery like $('class-name') it actively searched the DOM for that element and returns that element with all the jQuery prototype methods attached. When you're within the jQuery chain or event you don't have to rerun the DOM query you can use the context $(this)." By https://stackoverflow.com/users/185672/phil – chobela Jun 22 '20 at 08:18
186

For reference, try this! It works!

jQuery("classNameofDiv").click(function() {
    var contentPanelId = jQuery(this).attr("id");
    alert(contentPanelId);
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gemma
  • 1,861
  • 1
  • 11
  • 2
  • 16
    @gemma The other solution did not work for me but this one did. Thanks for being late. – HPWD Apr 25 '12 at 17:56
  • 3
    @dlackey it's the same for me, the other solution did not work on my firefox 12, but this one did. Thanks – linuxatico May 24 '12 at 12:43
  • 4
    The top answer doesn't seem to work for getting the ID of an element in an embedded SVG. `$(this).attr("id");` does. – Matt Fletcher Jun 26 '14 at 09:21
  • 3
    Keep in mind that if your click event is on an element with children, `e.target` will give you the exact element that caused the event to be fired even if it was a child, whereas `this` will give you the element that the event is attached to. – samrap Jul 12 '16 at 21:37
113

Though it is mentioned in other posts, I wanted to spell this out:

$(event.target).id is undefined

$(event.target)[0].id gives the id attribute.

event.target.id also gives the id attribute.

this.id gives the id attribute.

and

$(this).id is undefined.

The differences, of course, is between jQuery objects and DOM objects. "id" is a DOM property so you have to be on the DOM element object to use it.

(It tripped me up, so it probably tripped up someone else)

dun
  • 49
  • 6
dsch
  • 1,131
  • 1
  • 7
  • 2
108

For all events, not limited to just jQuery you can use

var target = event.target || event.srcElement;
var id = target.id

Where event.target fails it falls back on event.srcElement for IE. To clarify the above code does not require jQuery but also works with jQuery.

Alexander Elgin
  • 6,796
  • 4
  • 40
  • 50
Ally
  • 4,894
  • 8
  • 37
  • 45
  • 15
    Not using jQuery means less lines of code are run while getting the exact same result, as shown above. jQuery abstracts away js. This is the direct js answer, and look at the size! – xrDDDD Jul 30 '13 at 18:13
  • 1
    isn't it better to just use 'this' keyword which is always gonna give you access to properties of the element that invoked the event? – Morfidon Apr 29 '15 at 00:37
  • 9
    Just had to dig through the all the jQuery crap to get to this answer. Thanks. This is more relevant than ever: http://needsmorejquery.com/ – birgersp Jun 17 '16 at 07:39
59

You can use (this) to reference the object that fired the function.

'this' is a DOM element when you are inside of a callback function (in the context of jQuery), for example, being called by the click, each, bind, etc. methods.

Here is where you can learn more: http://remysharp.com/2007/04/12/jquerys-this-demystified/

sr01853
  • 6,043
  • 1
  • 19
  • 39
Espo
  • 41,399
  • 21
  • 132
  • 159
  • 4
    if you have a function like `$(html).click()` (this) will return the html object and not the clicked element – TCHdvlp Jun 28 '13 at 16:16
30

I generate a table dynamically out a database, receive the data in JSON and put it into a table. Every table row got a unique ID, which is needed for further actions, so, if the DOM is altered you need a different approach:

$("table").delegate("tr", "click", function() {
   var id=$(this).attr('id');
   alert("ID:"+id);  
});
Alexander Elgin
  • 6,796
  • 4
  • 40
  • 50
SMut
  • 301
  • 3
  • 2
  • 2
    Oh yeah, this is what I was looking for. It also works the same for the newer "on" since "delegate" is now deprecated. I had checkboxes created dynamically from DB data, and of course they all had different IDs which I needed to use to do something when clicked. I used this method here to get which ID was actually clicked. In old school JS I just passed the id from each checkbox in the checkbox's HTML, but can't do it that way with the jQuery event handler model. – Michael K Sep 14 '16 at 15:32
26

Element which fired event we have in event property

event.currentTarget

We get DOM node object on which was set event handler.


Most nested node which started bubbling process we have in

event.target

Event object is always first attribute of event handler, example:

document.querySelector("someSelector").addEventListener(function(event){

 console.log(event.target);
 console.log(event.currentTarget);

});

More about event delegation You can read in http://maciejsikora.com/standard-events-vs-event-delegation/

Maciej Sikora
  • 19,374
  • 4
  • 49
  • 50
13

The source element as a jQuery object should be obtained via

var $el = $(event.target);

This gets you the source of the click, rather than the element that the click function was assigned too. Can be useful when the click event is on a parent object EG.a click event on a table row, and you need the cell that was clicked

$("tr").click(function(event){
    var $td = $(event.target);
});
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Morvael
  • 3,478
  • 3
  • 36
  • 53
12

this works with most types of elements:

$('selector').on('click',function(e){
    log(e.currentTarget.id);
    });
Cris
  • 2,824
  • 24
  • 23
8

You can try to use:

$('*').live('click', function() {
 console.log(this.id);
 return false;
});
Darius
  • 137
  • 1
  • 3
8

Use can Use .on event

  $("table").on("tr", "click", function() {
                    var id=$(this).attr('id');
                    alert("ID:"+id);  
                });
Basant Rules
  • 785
  • 11
  • 8
7

In the case of delegated event handlers, where you might have something like this:

<ul>
    <li data-id="1">
        <span>Item 1</span>
    </li>
    <li data-id="2">
        <span>Item 2</span>
    </li>
    <li data-id="3">
        <span>Item 3</span>
    </li>
    <li data-id="4">
        <span>Item 4</span>
    </li>
    <li data-id="5">
        <span>Item 5</span>
    </li>
</ul>

and your JS code like so:

$(document).ready(function() {
    $('ul').on('click li', function(event) {
        var $target = $(event.target),
            itemId = $target.data('id');

        //do something with itemId
    });
});

You'll more than likely find that itemId is undefined, as the content of the LI is wrapped in a <span>, which means the <span> will probably be the event target. You can get around this with a small check, like so:

$(document).ready(function() {
    $('ul').on('click li', function(event) {
        var $target = $(event.target).is('li') ? $(event.target) : $(event.target).closest('li'),
            itemId = $target.data('id');

        //do something with itemId
    });
});

Or, if you prefer to maximize readability (and also avoid unnecessary repetition of jQuery wrapping calls):

$(document).ready(function() {
    $('ul').on('click li', function(event) {
        var $target = $(event.target),
            itemId;

        $target = $target.is('li') ? $target : $target.closest('li');
        itemId = $target.data('id');

        //do something with itemId
    });
});

When using event delegation, the .is() method is invaluable for verifying that your event target (among other things) is actually what you need it to be. Use .closest(selector) to search up the DOM tree, and use .find(selector) (generally coupled with .first(), as in .find(selector).first()) to search down it. You don't need to use .first() when using .closest(), as it only returns the first matching ancestor element, while .find() returns all matching descendants.

Isochronous
  • 1,076
  • 10
  • 25
  • 1
    Useful! I adjusted in my case because I just got a simple
  • and so I'd used itemId = $target.attr('id').
  • – Zappescu Oct 06 '15 at 16:25
  • Just be careful about using a simple ID attribute, as every ID needs to be unique on that page. So if you for some reason need to have two lists like that on that page, you'll likely wind up with duplicate IDs, which is a bad thing. That's why I tend to always use data-id just for future-proofing. – Isochronous Jul 21 '17 at 14:54