cucuru
cucuru

Reputation: 3698

how to get the td clicked having tr

I have a tr with a click listener. I want to know which td was the one clicked:

<tr class ="clickingClass">
  <td> first td </td>
  <td> second td </td>
</tr>
$(".clickingClass").on('click', function() {
  $(this).closest('td');
});

The above shows nothing. How can I do this?

Upvotes: 0

Views: 267

Answers (3)

Arg0n
Arg0n

Reputation: 8423

Why not bind to the tds instead?

$(".clickingClass td").on('click',function(){
   this //td
});

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because closest() goes up the DOM, not down it.

To do what you require you could instead attach the event handler directly on the td elements:

$(".clickingClass td").on('click', function() {
    // do something with $(this)...
});

Alternatively you could use the target property of the event passed to the handler function to determine which td was clicked:

$(".clickingClass").on('click', function(e) {
    // do something with $(e.target)...
});

Upvotes: 3

Super User
Super User

Reputation: 9642

You can use event.target for this

$(".clickingClass").on('click',function(event){
    alert(event.target);
});

Upvotes: 1

Related Questions