Monday, June 11, 2012

Getting the ID of the element that fired an event using JQuery

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

I'm thinking something like:

<script type="text/javascript" src="starterkit/jquery.js"></script>
<script type="text/javascript">
var test =;

<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.

Can anyone help with this?

Source: Tips4all


  1. In jQuery always refers to the element that triggered the event, where 'event' is the parameter passes to the function.

    $(document).ready(function() {
    $("a").click(function(event) {

    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");

  2. You can use (this) to reference the object the 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.

  3. I'm a tad late. lol. For reference, try this! It works!

    jQuery("classNameofDiv").click(function() {
    var contentPanelId = jQuery(this).attr("id");


  4. 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');

  5. The source element as a jQuery object should be obtained via

    var $el = $(;

    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

    var $td = $(;