jQuery: Add table row count column

In this post you will learn how to add a table column with a row count in it. If you are looking for "how to add a new table row", please refer to previous post.

Recently, a user on the jQuery mailing list asked how she could automatically add a table row counter into her table. She wanted to add a new column to her table and display the row number, so that her users could refer to row numbers while communicating. The user had the following HTML table markup:

Here, we are selecting first child td tags of all tr tags in a table with a transactions class. Then, we are iterating through them and passing a zero based index to the loop. While looping though the first row cells, we are adding new column just using .before('<td>'+(i+1)+'</td>') method. The resulting table would have the following markup:

However, for cases when tables have header rows and footer, the above script may not behave as expected. That is why we have to take into the consideration table headers and footers. So the code snippet above will become:

This code takes into the account the table headers and adds "#" header column for the counter. Still, this code is not as universal as it could have been. Let’s take into the account the possibility of row spans and multi line header rows and rewrite the code into the jQuery plugin with options.