I have an HTML table where each row represents a pany 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 pany and year values (e.g. item_1234_2011). This would make it possible, given an element's ID, to determine that elements corresponding pany and year IDs. But how would I locate all the elements associated with a given year?
I have an HTML table where each row represents a pany 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 pany and year values (e.g. item_1234_2011). This would make it possible, given an element's ID, to determine that elements corresponding pany and year IDs. But how would I locate all the elements associated with a given year?
Share Improve this question asked Nov 29, 2011 at 5:15 Jonathan WoodJonathan Wood 67.5k82 gold badges304 silver badges532 bronze badges 1- 1 Does this linke help: stackoverflow./questions/1237899/… – Sudhir Bastakoti Commented Nov 29, 2011 at 5:23
4 Answers
Reset to default 2Doing something like this $('td[id$=_2011]');
es to mind, if you use the format you specified.
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/3UgdA/
:nth-child()
pseudo selector could be handy. If you want to select the second column you can use $('table tr>td:nth-child(2)')
jsFiddle Example
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.