87

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);
djdd87
  • 67,346
  • 27
  • 156
  • 195
  • 2
    None of the answers take into account the possibility that the th might have a colspan greater than 1 which is my use case :( – Dexygen Sep 20 '15 at 01:07
  • 1
    @GeorgeJempty [My answer](http://stackoverflow.com/a/37312894/1127972) handles colspans. – doug65536 May 19 '16 at 02:46

6 Answers6

144
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());
user113716
  • 318,772
  • 63
  • 451
  • 440
  • 3
    if your putting more tables in your tables, use `.parent('table')` instead of `.closest('table')` – Dead.Rabit Jun 06 '13 at 10:07
  • @bradvido - My [**answer**](https://stackoverflow.com/a/46139306/104380) takes that into account – vsync Sep 10 '17 at 09:45
10
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
  • 43,763
  • 16
  • 104
  • 144
5

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

var tdIndex = $td.index() + 1;
var $th = $('#table tr').find('th:nth-child(' + tdIndex + ')');
rebelliard
  • 9,592
  • 6
  • 47
  • 80
  • 1
    Remember that `.index()` is zero-based, and `nth-child` is one-based. So the result would be off by one. :o) – user113716 Aug 19 '10 at 16:18
5

Solution that handles colspan

I have a solution based on matching the left edge of the td to the left edge of the corresponding th. It should handle arbitrarily complex colspans.

I modified the test case to show that arbitrary colspan is handled correctly.

Live Demo

JS

$(function($) {
  "use strict";

  // Only part of the demo, the thFromTd call does the work
  $(document).on('mouseover mouseout', 'td', function(event) {
    var td = $(event.target).closest('td'),
        th = thFromTd(td);
    th.parent().find('.highlight').removeClass('highlight');
    if (event.type === 'mouseover')
      th.addClass('highlight');
  });

  // Returns jquery object
  function thFromTd(td) {
    var ofs = td.offset().left,
        table = td.closest('table'),
        thead = table.children('thead').eq(0),
        positions = cacheThPositions(thead),
        matches = positions.filter(function(eldata) {
          return eldata.left <= ofs;
        }),
        match = matches[matches.length-1],
        matchEl = $(match.el);
    return matchEl;
  }

  // Caches the positions of the headers,
  // so we don't do a lot of expensive `.offset()` calls.
  function cacheThPositions(thead) {
    var data = thead.data('cached-pos'),
        allth;
    if (data)
      return data;
    allth = thead.children('tr').children('th');
    data = allth.map(function() {
      var th = $(this);
      return {
        el: this,
        left: th.offset().left
      };
    }).toArray();
    thead.data('cached-pos', data);
    return data;
  }
});

CSS

.highlight {
  background-color: #EEE;
}

HTML

<table>
    <thead> 
        <tr>
            <th colspan="3">Not header!</th>
            <th id="name" colspan="3">Name</th>
            <th id="address">Address</th>
            <th id="address">Other</th>
        </tr>
    </thead> 
    <tbody>
        <tr>
            <td colspan="2">X</td>
            <td>1</td>
            <td>Bob</td>
            <td>J</td>
            <td>Public</td>
            <td>1 High Street</td>
            <td colspan="2">Postfix</td>
        </tr>
    </tbody>
</table>
doug65536
  • 6,562
  • 3
  • 43
  • 53
  • I expanded the test case to simultaneously use arbitrary combinations of `colspan` in the headers and the rows, and it still worked. I'd be happy to hear about any cases you can find that will not work with this. – doug65536 May 19 '16 at 04:07
3

Pure JavaScript's solution:

var index = Array.prototype.indexOf.call(your_td.parentNode.children, your_td)
var corresponding_th = document.querySelector('#your_table_id th:nth-child(' + (index+1) + ')')
jeromej
  • 10,508
  • 2
  • 43
  • 62
3

Find matching th for a td, taking into account colspan index issues.

document.querySelector('table').addEventListener('click', onCellClick)

function onCellClick( e ){
  if( e.target.nodeName == 'TD' )
    console.log( get_TH_by_TD(e.target) )
}

function get_TH_by_TD( tdNode ){
   var idx = [...tdNode.parentNode.children].indexOf(tdNode), // get td index
       thCells = tdNode.closest('table').tHead.rows[0].cells, // get all th cells
       th_colSpan_acc = 0 // accumulator

   // iterate all th cells and add-up their colSpan value
   for( var i=0; i < thCells.length; i++ ){
      th_colSpan_acc += thCells[i].colSpan
      if( th_colSpan_acc >= (idx + tdNode.colSpan) ) break
   }
 
   return thCells[i]
}
table{ width:100%; }
th, td{ border:1px solid silver; padding:5px; }
<p>Click a TD:</p>
<table>
    <thead> 
        <tr>
            <th colspan="2"></th>
            <th>Name</th>
            <th colspan="2">Address</th>
            <th colspan="2">Other</th>
        </tr>
    </thead> 
    <tbody>
        <tr>
            <td>X</td>
            <td>1</td>
            <td>Jon Snow</td>
            <td>12</td>
            <td>High Street</td>
            <td>Postfix</td>
            <td>Public</td>
        </tr>
    </tbody>
</table>
vsync
  • 118,978
  • 58
  • 307
  • 400