I have a table with a "header" that user regular tr tags (not th). I need to find header "Col2" and then to each cell under Col2 add an anchor. I can do $("td:contains('Col2'))
to find the header, but the data rows could also have "Col2". How would I search just the first row and then loop through the row cells?
<table>
<tr>
<td>Col1</td>
<td>Col2</td>
</tr>
<tr>
<td>Data1</td>
<td>Data2</td>
</tr>
<tr>
<td>Data3</td>
<td>Data4</td>
</tr>
</table>
Becomes:
<table>
<tr>
<td>Col1</td>
<td>Col2</td>
</tr>
<tr>
<td>Data1</td>
<td><a href="?Data2">Data2</a></td>
</tr>
<tr>
<td>Data3</td>
<td><a href="?Data4">Data4</a></td>
</tr>
</table>
Edit: I actually have more than one table in the same page. :first
only matches the first row in the first table.
Update: Here is how I finally got it working. Thanks to everyone for your help! With a little from each of you and a little from the API docs it works. Now that I'm starting to get the hang of it, I can't imagine the pain of doing this without jQuery.
$('table').each(function(i, table) {
$(table).find('tr:first > td:contains("Col2")').each(function() {
var cellIndex = $(this).index() + 1;
$(table).find('tr:not(:first) > td:nth-child(' + cellIndex + ')').wrapInner(function() {
return $('<a />', { 'href': '?data=' + $(this).text() });
});
});
});