Given the following table, how would I get the corresponding table header for each td element?
<table>
<thead>
<tr>
<th id="name">Name</th>
<th id="address">Address</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bob</td>
<td>1 High Street</td>
</tr>
</tbody>
</table>
Given that I currently have any of the td
elements available to me already, how could I find the corresponding th
element?
var $td = IveGotThisCovered();
var $th = GetTableHeader($td);
That's simple, if you reference them by index. If you want to hide the first column, you would:
Copy code
The reason I first selected all table rows and then both td's and th's that were the n'th child is so that we wouldn't have to select the table and all table rows twice. This improves script execution speed. Keep in mind,
nth-child()
is1
based, not0
.You can do it by using the td's index:
Or a little bit simplified
Solution that handles
colspan
I have a solution based on matching the left edge of the
td
to the left edge of the correspondingth
. It should handle arbitrarily complex colspans.I modified the test case to show that arbitrary
colspan
is handled correctly.Live Demo
JS
CSS
HTML
Find matching
th
for atd
, taking into accountcolspan
index issues.It would be best to use an id to reference the table if there is more than one.