0

function mainClick(){
console.log(event.target.innerHTML);
console.log(event.target.tagName);
}
<table onclick="mainClick()">
<tr>
  <th>ID</th>
  <th>Name</th>
</tr>
<tr>
  <td>8475</td>
  <td>yogesh</td>
</tr>
<tr>
  <td>7512</td>
  <td>tarun</td>
</tr>
<tr>
  <td>3322</td>
  <td>aman</td>
</tr>
<tr>
  <td>1232</td>
  <td>vishesh</td>
  </tr>
<tr>
  <td>9877</td>
  <td>rahul</td>
</tr>
</table>


 

I'm using concept of event delegation which mean adding event listener to parent element instead of adding to descendent elements. Listener will fire whenever event is triggered on descendent element due to bubbling.

I'm able to retrieve html content and tag name but how can I find out which row number is clicked in a table?

Yogesh Yadav
  • 723
  • 6
  • 21
  • Does this answer your question? [How to tell which row number is clicked in a table?](https://stackoverflow.com/questions/4524661/how-to-tell-which-row-number-is-clicked-in-a-table) – JBaczuk Aug 26 '21 at 15:50

1 Answers1

3

event.target.parentElement.rowIndex works like a charm.

function mainClick(){
console.log(event.target.parentElement.rowIndex);
console.log(event.target.innerHTML);
console.log(event.target.tagName);
}
<table onclick="mainClick()">
<tr>
  <th>ID</th>
  <th>Name</th>
</tr>
<tr>
  <td>8475</td>
  <td>yogesh</td>
</tr>
<tr>
  <td>7512</td>
  <td>tarun</td>
</tr>
<tr>
  <td>3322</td>
  <td>aman</td>
</tr>
<tr>
  <td>1232</td>
  <td>vishesh</td>
  </tr>
<tr>
  <td>9877</td>
  <td>rahul</td>
</tr>
</table>


 
Yogesh Yadav
  • 723
  • 6
  • 21