Detect Table Row Index with JavaScript
Sometimes it happens that you need exact table row index, so you can manipulate data in the HTML table on the client-side. Since the AJAX is so hot (very hot here in web.burza), it’s the matter of seconds ‘till someone will need this kind of information. The rowIndex property is far less known, but potentially useful method and it’s compatible with most of the browsers. Here is a quick example of its’ use.
<html>
<head>
<title>Row indexes</title>
<script type="text/javascript">
onload = function() {
if (!document.getElementsByTagName || !document.createTextNode) return;
var rows = document.getElementById('my_table').getElementsByTagName('tbody')[0].getElementsByTagName('tr');
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function() {
alert(this.rowIndex + 1);
}
}
}
</script>
</head>
<body>
<table id="my_table">
<tbody>
<tr><td>first row</td></tr>
<tr><td>second row</td></tr>
</tbody>
</table>
</body>
</html>
Excuse me for not explaining it more deeply. After all, this is meant to be a quick reference for advanced Ajaxians. Feel free to develop discussion in the comments.

2 Comments
Well, how about that! I didn’t know that there actually was a rowIndex property, silly me. I don’t really deal with tables a whole lot, so I’ve never needed this, but it’s good to know it’s around. I honestly need to start working with data tables and Ajax more often — lately I’ve been doing lots of Ajax, but nowhere near as much data table manipulation/processing. Thanks for this little bit.
Comment (#) by Jonathan Fenocchi — 18th May 2005.
A good starting point in discovering DOM/JavaScript object properties and relations between document nodes is DOM inspector bundled with Firefox.
Comment (#) by marko — 18th May 2005.
Sorry, the comment form is closed at this time, but if you have anything to say, please send me a message.