Finding td element position in table row

How would I go about finding a td element's position in a table row? I have seen this code suggested, but is there a way to do this with having each td tag contain an onclick event?

<table>
  <tr>
    <td onclick="myFunction(this)">Click to show cellIndex</td>
    <td onclick="myFunction(this)">Click to show cellIndex</td>
    <td onclick="myFunction(this)">Click to show cellIndex</td>
    <td onclick="myFunction(this)">Click to show cellIndex</td>
 </tr>
</table>

<script>
 function myFunction(x) {
   alert("Cell index is: " + x.cellIndex);
}
</script>

I have a grid of images and I am trying to see which images in the grid have been clicked. I tried this:

$('td img').on('click', function(x){
   console.log("Cell index is: " + x.cellIndex); 
});

But it just logs undefined

Answers 1

  • $('td img').on('click', function(e) {
      var td = $(this).parent();
      var tr = td.parent();
      
      var children = tr.children().length;
      
      var tdIndex = td.index() + 1;
      var trIndex = tr.index();
      
      console.log((trIndex * children) + tdIndex);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table>
      <tr>
        <td><img src="1.jpg" /></td>
        <td><img src="2.jpg" /></td>
      </tr>
      <tr>
        <td><img src="1.jpg" /></td>
        <td><img src="2.jpg" /></td>
      </tr>
    </table>


Related Articles