Sean Taylor Sean Taylor - 6 months ago 45
Javascript Question

How to get a table cell value using jQuery?

I am trying to work out how to get the value of table cell for each row using jQuery.

My table looks like this:

<table id="mytable">
<tr>
<th>Customer Id</th>
<th>Result</th>
</tr>
<tr>
<td>123</td>
<td></td>
</tr>
<tr>
<td>456</td>
<td></td>
</tr>
<tr>
<td>789</td>
<td></td>
</tr>
</table>


I basically want to loop through the table, and get the value of the
Customer Id
column for each row.

In the code below I have worked out that I need to do this to get it looping through each row, but I'm not sure how to get the value of the first cell in the row.

$('#mytable tr').each(function() {
var cutomerId =
}

Answer

If you can, it might be worth using a class attribute on the TD containing the customer ID so you can write:

$('#mytable tr').each(function() {
    var customerId = $(this).find(".customerIDCell").html();    
 });

Essentially this is the same as the other solutions (possibly because I copypasted), but has the advantage that you won't need to change the structure of your code if you move around the columns, or even put the customer ID into a < span >, provided you keep the class attribute with it.

By the way, I think you could do it in one selector:

$('#mytable .customerIDCell').each(function()
{
  alert($(this).html());
});

If that makes things easier

Comments