Dane
Dane

Reputation: 287

JQuery return find in conjunction with eq

I'm trying to list the table cells in a specific header.

I pass in a table and then I used a passed in index to determine the header, this part is fine. The problem is when I try to get the cells from here then it's not working.

var $tableCells = $table.eq(index).find('td')

If I get the cells before I narrow down the headers then it works fine:

var $tableCells = $table.find('td')

It's most likely something simple but I'm new to JQuery.

Any suggestions?

Upvotes: 0

Views: 69

Answers (1)

Jamiec
Jamiec

Reputation: 136104

You're after the :nth-child selector. It can be used like the below to get the n'th td in each row of a table.

Note: the index passed to that selector, unlike most of javascript, is 1-based. so nth-child(1) will get the first child.

var $table = $('table');
var index = 1;

var $tableCells = $table.find('tr td:nth-child(' + index + ')');
$tableCells.each(function(){
   alert($(this).html()); // alerts "row0 cell0" then "row1 cell0"
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tr>
    <td>row0 cell0</td>
    <td>row0 cell1</td>
    <td>row0 cell2</td>
  </tr>
  <tr>
    <td>row1 cell0</td>
    <td>row1 cell1</td>
    <td>row1 cell2</td>
  </tr>
</table>

Upvotes: 1

Related Questions