Reputation: 67193
I have an HTML table where each row represents a company and each column represents a year.
Returning a collection of all the cells in a row will be easy. I could give the row an ID or class and look for all the <td>
elements within that row. But how would I get all the elements that correspond to a particular year (column)?
I was thinking I could make up element IDs using the company and year values (e.g. item_1234_2011). This would make it possible, given an element's ID, to determine that elements corresponding company and year IDs. But how would I locate all the elements associated with a given year?
Upvotes: 3
Views: 2421
Reputation: 6188
The first column would look something like:
$('tr > td:first-child', yourTable);
While associating with a year should look like:
var getCellsByYear = function (year, column) {
column = column || 0; // Could set a reasonable default.
return $('tr > td:nth-child("' + column + '"):content("' + year + '")');
};
Edit switching to nth-child
, since that seems more appropriate.
Upvotes: 2
Reputation: 4164
Doing something like this $('td[id$=_2011]');
comes to mind, if you use the format you specified.
Upvotes: 2
Reputation: 32158
:nth-child()
pseudo selector could be handy. If you want to select the second column you can use $('table tr>td:nth-child(2)')
Upvotes: 2
Reputation: 37516
This simple example should get you going. Suppose you had the following markup, and you wanted the middle column of table cells.
Markup
<table id="stuff">
<tr>
<td>a</td>
<td>d</td>
<td>g</td>
</tr>
<tr>
<td>b</td>
<td>e</td>
<td>h</td>
</tr>
<tr>
<td>c</td>
<td>f</td>
<td>i</td>
</tr>
</table>
You can select the cells (d, e, f) with the following jQuery:
$('td:eq(1)', $('#stuff tr')).each(function()
{
console.log($(this).html());
});
Working example here: http://jsfiddle.net/3UgdA/
Upvotes: 2