Dynamically adding table row count number using JavaScript and jQuery

Now available as a rowCount jQuery plugin.

Recently on jQuery mailing list a user asked how he/she could add a row count in their table automatically. So I wrote a code snippet which looks like this:

$(document).ready(function(){
  $("table").each(function(){
    if($(this).is('table')){
      $('thead th:first-child, thead td:first-child', this).each(function(){
        if($(this).is('td'))
          $(this).before('<td>#</td>');
        else if($(this).is('th'))
          $(this).before('<th>#</th>');
      });
      $('tbody td:first-child', this).each(function(i){
        $(this).before('<td>'+(i+1)+'</td>');
      });
    }
  });
});

This code was for specific case, where there is only one table on the page and it has only one row in its header. That is why I took into the account the possibility of row spans and multi line rows in header and rewrote the code. Then made a plugin out of it.

So, here is the final code:

(function($){
  $.fn.extend({
    addCount: function() {
      return $(this).each(function(){
        if($(this).is('table')){
          $('thead th:first, thead td:first', this).each(function(){
            if($(this).is('td'))
              $(this).before('<td rowspan="'+$('thead tr').length+'">#</td>');
        else if($(this).is('th'))
              $(this).before('<th rowspan="'+$('thead tr').length+'">#</th>');
          });
          $('tbody td:first-child', this).each(function(i){
        $(this).before('<td>'+(i+1)+'</td>');
          });
      }
      });
    }
  });
})(jQuery);

To apply it to your tables use this code:

$('table').addCount(); 
$('.some-table-class').addCount(); 
$('#some-table-id').addCount();