Ankur
Ankur

Reputation: 51100

How to pass Id of a div that is clicked to a function that handles the click in jQuery

I want to my div ids to correspond to items in a database. Based on an id my app will pull appropriate content from a database.

Hence when I use .click() to handle a click I need to pass the Id of the div being clicked to the function that handles it. How do I do this?

Upvotes: 2

Views: 578

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

In the context of a click handler this corresponds to the DOM element which was clicked. You can use it to extract the id:

$('div').click(function() {
    // Get the id of the clicked div
    var id = this.id;
    // Do something with it ...
});

Upvotes: 2

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827256

Inside your click event handler function, the context (the this keyword) refers to the DOM element that triggered the event, you can get the id from it, for example:

$('div[id]').click(function () { // all divs that have an id attribute
  var id = this.id; // or $(this).attr('id');

  someOtherFunction(id);
});

Upvotes: 6

Related Questions