7

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?

0

1 Answer 1

14

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 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 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 td").length; index++){
   cells.push($("table td").get(index).html());
};

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

Sign up to request clarification or add additional context in comments.

4 Comments

+1 but in your example, "table tr td" is unnecessary (and slower). "table td" is enough.
thanks for the info. How would I manage skipping the first row (headers)? I am sending the array to a web service (prob WCF).
there's more than one method to skip over the first row. I included a couple - see my edited answer. Hope this helps!
Matt -- you're very welcome, and @ChetanSastry you're absolutely right -- updated the code. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.