Detect Table Row Index with JavaScript
Every once in a while, a project we work on will require us to detect a table row in order to manipulate the data on the client-side, without having to reload the whole page. This is relatively easy to achieve using JavaScript and rowIndex; a useful JS method that’s compatible with almost every browser.
The rowIndex
is a little known property, but nevertheless it’s a useful JS method because it is compatible with almost every browser.
Below is a quick demo.
<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>
How do you like this? What is your typical use case? Feel free to leave a comment.