Mohammad Saberi
Mohammad Saberi

Reputation: 13166

How to detect current element id in jQuery?

I have some HTML codes:

<input type="button" id="btn1" class="myButton" value="Button 1"/>
<input type="button" id="btn2" class="myButton" value="Button 2"/>

I need to run a jQuery function whenever user click each button, and I have to do it using their class.

$('.myButton').click(function() {
   // do something
});

But what I should to do, depends on the current element Id.

My question is that how can I detect which element called this function? I need to know its id.

Upvotes: 26

Views: 88258

Answers (6)

Emre Erkan
Emre Erkan

Reputation: 8482

You can use this to access current element and then this.id will give you the id of the current element.

$(document).on('click', '.myButton', function(e) {
    alert(this.id);
});

Upvotes: 40

Aghyad Algllad
Aghyad Algllad

Reputation: 1805

$('.myButton').on('click',(e)=> {

 if (e.target.id === "btn1") {
     ...
}    

});

Upvotes: 0

Jmunoz Dev
Jmunoz Dev

Reputation: 461

With jQuery i found this working:

$(this).prop('id')

Upvotes: 4

andreapier
andreapier

Reputation: 2958

Look at this. You can just use the attr() method to get the id of the clicked element as you bind a click callback to EVERY element with .myButton class.

Upvotes: 2

Armin
Armin

Reputation: 15958

If you want to keep in jquery context, you could use this snippet:

$('.myButton').click(function() {
    alert($(this).attr('id'));
});

With this way you are a bit more flexible.

Upvotes: 27

Didier Ghys
Didier Ghys

Reputation: 30666

this in the event handler is the element that was clicked:

$('.myButton').click(function() {

   if (this.id === "btn1") {
       ...
   }    

});

Upvotes: 1

Related Questions