Sachin Vairagi Sachin Vairagi - 4 months ago 10
Javascript Question

How to get which td clicked in JavaScript?

I've got the following table:

<table>
<tbody>
<tr data-uom_id="1" id="id-742">
<td style="width: 15%; vertical-align: middle; display: none;"><img src="left-arrow.png>"</td>
<td style="width: 70%; text-align: left;" class="center">some text here</td>
<td style="width: 15%; vertical-align: middle;"><img src="right-arrow.png></td>
</tr>
</tbody>
</table>


Here my
<tr>
element has 3
<td>
. Can I get which
<td>
is clicked? Please check attached image for more clarification.

enter image description here

Answer

You can try the following code:

Edit - changed the code as per requirement

function whichOne() {
    //alert(this.id);
    document.getElementById("center").style.textAlign = this.id;
} 

document.getElementById('left').onclick = whichOne;
document.getElementById('right').onclick = whichOne;
document.getElementById('center').onclick = whichOne;
<table border="1">
  <tbody>
   <tr>
     <td style="width: 15%;" id="left">1</td>
     <td style="width: 70%; text-align: center;" id="center">2</td>
     <td style="width: 15%;" id="right">3</td>
   </tr>
  </tbody>
</table>

Comments