views:

808

answers:

1

What's the best method for looping through a table, grabbing all the data in the cells, but skipping the <th>? Do I put the data in an array?

+4  A: 

Say you have a table that looks like this:

<table>
    <tr>
        <td>Information 1</td>
        <td>Information 2</td>
    </tr>
</table>

You could do something like this:

var cells = new Array();
$("table tr td").each(function(){
   cells.push($(this).html());
});

What exactly are you looking to do with the data?


The easiest thing to do to skip the headers would to just remove them from the array after the loop is done.

After the code is done, you can run something like this:

cells = cells.slice(1, cells.length);

This will set the array to a copy of itself, minus the first element.

Alternatively, when you initially loop through it, only store the information if the index is greater than zero:

var cells = new Array();
$("table tr td").each(function(index){
   if(index > 0){
      cells.push($(this).html());
   }
});

And finally, if you'd like to go with a more traditional javascript solution that does not require a condition:

var cells = new Array();
for(index = 1; index < $("table tr td").length; index++){
   cells.push($("table tr td").get(index).html());
};

That way, you're starting from the second row.

yuval
+1 but in your example, `"table tr td"` is unnecessary (and slower). `"table td"` is enough.
Chetan Sastry
thanks for the info. How would I manage skipping the first row (headers)? I am sending the array to a web service (prob WCF).
Matt
there's more than one method to skip over the first row. I included a couple - see my edited answer. Hope this helps!
yuval
thanks a million!
Matt