Andrew Guenther
Andrew Guenther

Reputation: 1492

How to access a calling element's id in a jQuery click() function

So I am binding a .click() function to a css class, but I want to be able to access the calling element's id from inside this function when it is called. What is the best way to do this?

Upvotes: 2

Views: 1367

Answers (2)

mu is too short
mu is too short

Reputation: 434615

You can pull it right out of this:

$(selector).click(function() {
    var id = this.id;
    // Do interesting things.
});

The this in a jQuery click callback is just a DOM object that exposes its attributes as object properties.

Upvotes: 3

Ibu
Ibu

Reputation: 43810

You can use the this key word:

$(".elementClass").click(function () {
   var currentElement = $(this); // refers to the current element

   var theId = currentElement.attr("id");
});

Upvotes: 1

Related Questions