Out Now

Loop through rows and cells in a table using JQuery

It is possible to loop through the rows and cells in a HTML table using JQuery.

This can be really useful for parsing data you might not be able to change the output of or applying some clever formatting to a table after it has been output.

The code below assumes that you know the number of columns in your table and that you know which one you want to address. In this example, we are looking at the value of cell 8.


$(document).ready(function() {
    var row = 1;
    $('table tr').each(function(){
        var cell = 'table tr:nth-child(' + row + ') td:nth-child(8)';
        alert(cell.text());
        row = row + 1;
    });
});

The trick is to keep a count of the row that you are on, so that you can use the nth-child function of the table to find it and then to address the nth-child of that nth-child to find a particular cell.

Merged cells or colspans are likely to screw this code up, so try to avoid these if you can!

Leave a Reply