Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 984
milk Avatar asked Sep 12 '09 15:09

milk


4 Answers

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 + "]");
});
like image 89
adrian Avatar answered Mar 10 '23 09:03

adrian


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(',') );
});
like image 31
vol7ron Avatar answered Mar 10 '23 08:03

vol7ron


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(''));
})
like image 42
Alex Gyoshev Avatar answered Mar 10 '23 08:03

Alex Gyoshev


In jQuery 1.6 :

$(this).prop('cellIndex')
like image 35
user643862 Avatar answered Mar 10 '23 10:03

user643862