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.

<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);
<table id="my_table">
    <tr><td>first row</td></tr>
    <tr><td>second row</td></tr>

How do you like this? What is your typical use case? Feel free to leave a comment.

Marko Dugonjić is a designer specialized in user experience design, web typography and web standards. He runs a nanoscale user interface studio Creative Nights and organizes FFWD.PRO, a micro-conference and workshops for web professionals.

Interested in more content like this?