views:

66

answers:

3

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);
+8  A: 
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());
patrick dw
+1 Perfect. Thank you. I went with the simplified version.
GenericTypeTea
@GenericTypeTea - You're welcome. :o)
patrick dw
Mark as the solution. It's one sexy answer indeed. :o
Rafael Belliard
Done. I was trying to do it up until I left work. Wasn't going to stay just to accept any answer :) thanks again patrick.
GenericTypeTea
@GenericTypeTea - Wasn't worried about it. That comment was from Rafael. Appreciated, but not necessary considering your accept rate. :o)
patrick dw
+1  A: 

You can do it by using the td's index:

var tdIndex = $td.index() + 1;
var $th = $('#table tr').find('th:nth-child(' + tdIndex + ')');
Rafael Belliard
Remember that `.index()` is zero-based, and `nth-child` is one-based. So the result would be off by one. :o)
patrick dw
@patric thanks for the errata.
Rafael Belliard
+1  A: 
var $th = $("table thead tr th").eq($td.index())

It would be best to use an id to reference the table if there is more than one.

Adam