dzm
dzm

Reputation: 23534

Iterate through second columns in a table in jQuery

I have table in the dom that looks like this

<div id="table">
<table>
<tr>
  <td>a</td>
  <td>b</td>
  <td>c</td>
  <td>d</td>
</tr>
<tr>
  <td>a</td>
  <td>b</td>
  <td>c</td>
  <td>d</td>
</tr> 
</div>

I want to iterate through this table, such as $('#table').each(function(){}) but I only want to iterate through the second column. So the ones which in this example have a value of b.

Any ideas how to do this?

Thank you!

Upvotes: 11

Views: 31169

Answers (3)

Ian
Ian

Reputation: 50905

Using the nth-child selector in jQuery, this should work:

$("#table").find("td:nth-child(2)").each(function () {

});

This uses the nth-child selector, http://api.jquery.com/nth-child-selector/ , which as the link states, would select all <td> elements that are the 2nd child of their parent (which would be a <tr>).

Here's a fiddle that demonstrates it: http://jsfiddle.net/GshRz/

If you are looking for a selector that gets the <td>s that are only immediately in the table (like not in a nested table), then use something like:

$("#table").children("tbody").children("tr").children("td:nth-child(2)").each(function () {

});

http://jsfiddle.net/GshRz/1/

Depending on your structure (where you might include a <thead>), you could use .children("thead, tbody") instead of just .children("tbody").

Also, in case you want to be grabbing several columns, it could be easier to select the <tr> elements and then get their children <td> elements. For example:

$("#table1").children("tbody").children("tr").each(function (i) {
    var $this = $(this);
    var my_td = $this.children("td");
    var second_col = my_td.eq(1);
    var third_col = my_td.eq(2);
    console.log("Second Column Value (row " + i + "): " + second_col.html());
    console.log("Third Column Value (row " + i + "): " + third_col.html());
});

http://jsfiddle.net/GshRz/2/

What selectors you use and where, is up to the structure and content of your table. So remember to differentiate between children and find, and nth-child and eq.

Upvotes: 13

Anujith
Anujith

Reputation: 9370

$("#table td:nth-child(2)").each(function (index) {
   alert('Row no. ' + (index+1) + ', Column 2 : ' + $(this).html());
});

Sample

Upvotes: 1

phnkha
phnkha

Reputation: 7872

Try this:

$("table tr td:nth-child(2)").each(function () {

});

Upvotes: 28

Related Questions