milk
milk

Reputation: 139

How to get a <td> 's position in a table using JQuery?

For example:

<table>
<tr><td>1,1</td><td>2,1</td></tr>
<tr><td>2,1</td><td>2,2</td></tr>
</table>

I want to using the following function:

$("td").click(function(){
alert(xxxx)
})

to get the <td> `s position when clicked, but how?

Upvotes: 12

Views: 31804

Answers (5)

antelove
antelove

Reputation: 3358

$("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>

Upvotes: 1

adrian
adrian

Reputation: 1751

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

Lets you do this, which is pretty readable:

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

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

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

Upvotes: 8

user643862
user643862

Reputation: 95

In jQuery 1.6 :

$(this).prop('cellIndex')

Upvotes: 3

vol7ron
vol7ron

Reputation: 42149

The index function called with no parameters will get the position relative to its siblings (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(',') );
});

Upvotes: 24

Alex Gyoshev
Alex Gyoshev

Reputation: 11977

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(''));
})

Upvotes: 16

Related Questions