Shades88
Shades88

Reputation: 8360

How to get ID of an element in jQuery, which is being clicked

I have a scenario, wherein, I have a table and in some columns I have some hidden divs. Now in one of these columns I have a Div which contains another hidden div. Now I cannot apply a generalised function which will just show all divs within a particular row or even within a particular column. I would like to have a function which would detect the id or class of element which is being clicked upon. How to go about this ?

Upvotes: 2

Views: 300

Answers (6)

Safran Ali
Safran Ali

Reputation: 4497

do this, onclick event of the element:

<div id="div1" onclick="getId();"> </div>;

function getId(){
     var currentId = $(this).attr('id');
}

Upvotes: 2

JanLikar
JanLikar

Reputation: 1306

You do it like this;

$("div").click(function(){

alert($(this).attr("id"));

});

Upvotes: 2

genesis
genesis

Reputation: 50966

$(".class").click(function(){
    var clicked = $(this).attr('id');
});

could help

Upvotes: 0

medkg15
medkg15

Reputation: 1595

This will log the ID of the element that was clicked. You can then add additional logic as shown to handle the "show" functionality.

$('div').click(function(){
    console.log($(this).attr('id');
    //other logic here
});

Upvotes: 0

M. Cypher
M. Cypher

Reputation: 7066

Like this?

$(<selector>).click(function() {
  id = $(this).attr('id');
});

Upvotes: 2

user188654
user188654

Reputation:

$('div').bind('click', function(){ // Make this part as specific as it can be
    console.log($(this).attr('id'));
});

You can make your initial selector a bit more restrictive because selecting all divs on a page and assigning an event handler to them is not such a good idea.

Upvotes: 0

Related Questions