Get clicked element using jQuery on event?

Devil's Advocate picture Devil's Advocate · Apr 18, 2013 · Viewed 175.8k times · Source

I'm using the following code to detect when a dynamically generated button is clicked.

$(document).on("click",".appDetails", function () {
    alert("test");
});

Normally, if you just did $('.appDetails').click() you could use $(this) to get the element that was clicked on. How would I accomplish this with the above code?

For instance:

$(document).on("click",".appDetails", function () {
    var clickedBtnID = ??????
    alert('you clicked on button #' + clickedBtnID);
});

Answer

bipen picture bipen · Apr 18, 2013

As simple as it can be

Use $(this) here too

$(document).on("click",".appDetails", function () {
   var clickedBtnID = $(this).attr('id'); // or var clickedBtnID = this.id
   alert('you clicked on button #' + clickedBtnID);
});