GenericTypeTea GenericTypeTea - 6 months ago 27
Javascript Question

How can I get the corresponding table header (th) from a table cell (td)?

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);

Answer
var $th = $td.closest('tbody').prev('thead').find('> tr > th:eq(' + $td.index() + ')');

Or a little bit simplified

var $th = $td.closest('table').find('th').eq($td.index());
Comments