geeky_monster
geeky_monster

Reputation: 8792

Jquery - How do I access the element that was clicked to run a function?

I am using jQuery . I have some code like below -

----HTML-----

<table> 
<tr>
<td class="cell" id="cell1" ></td>
<td class="cell" id="cell2"></td>
<td class="cell" id="cell3" ></td>

</tr>

<tr>
<td class="cell" id="cell4"></td>
<td class="cell" id="cell5"></td>
<td class="cell" id="cell6"></td>

</tr>

</table>

---JS----

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

do_something();

}

function do_something(){

// I want to print the id of the cell that was clicked here . 

}

How do I access the element that caused the function to be run ? For eg in the above code , I want to access the id of the cell that was clicked from inside the function do_Something()

Upvotes: 0

Views: 137

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382132

$(".cell").click(function() {
    do_something(this); // this is the clicked element
});
function do_something(element){
    console.log(element.id); // open the console to see the result
}

Of course it would be simpler to simply call it directly :

$(".cell").click(do_something);  
function do_something(){
    console.log(this.id); // open the console to see the result
}

or

$(".cell").click(function(){
    console.log(this.id); // open the console to see the result
});

Upvotes: 3

Related Questions