[ACCEPTED]-How to get a <td> 's position in a table using JQuery?-html-table

Accepted answer
Score: 24

The index function called with no parameters 2 will get the position relative to its siblings 1 (no need to traverse the hierarchy).

$('td').click(function(){   
   var $this = $(this);
   var col   = $this.index();
   var row   = $this.closest('tr').index();

   alert( [col,row].join(',') );
});
Score: 16

Core / index

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

    var column = $(this).parent().children().index(this);
    var row = $(this).parent().parent().children().index(this.parentNode);

    alert([column, ',', row].join(''));
})

0

Score: 8

As per this answer, DOM Level 2 exposes cellIndex and rowIndex properties 2 of td and tr elements, respectively.

Lets you 1 do this, which is pretty readable:

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

    var column = this.cellIndex;
    var row = $(this).parentNode.rowIndex;

    alert("[" + column + ", " + row + "]");
});
Score: 3

In jQuery 1.6 :

$(this).prop('cellIndex')

0

Score: 1

$("td").click(function(e){
  alert(e.target.parentElement.rowIndex + " " + e.target.cellIndex)
});
tr, td {
  padding: 0.3rem;
  border: 1px solid black
}

table:hover {
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>0, 0</td>
    <td>0, 1</td>
    <td>0, 2</td>
  </tr>
  <tr>
    <td>1, 0</td>
    <td>1, 1</td>
    <td>1, 2</td>
  </tr>
</table>

0

More Related questions