Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); 
like image 782
djdd87 Avatar asked Aug 19 '10 16:08

djdd87


People also ask

How do I find the header of a table?

Go to Table Tools > Design on the Ribbon. In the Table Style Options group, select the Header Row check box to hide or display the table headers.

What are the difference between table cell TD and table header th?

The TH and TD elements are used for table cells. TH is used for table header cells while TD is used for table data cells. This distinction gives user agents a means to render such cells distinctly, for instance by using a larger or heavier font for header cells.

How do you define a header cell in a table?

Header cells are those that contain the information that is critical to understanding the raw data in a table. For example the number 210 is meaningless on its own, but becomes information if you know that it is the data for a) the number of properties in b) a given street.


2 Answers

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()); 
like image 82
user113716 Avatar answered Oct 06 '22 11:10

user113716


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.

like image 32
Adam Avatar answered Oct 06 '22 12:10

Adam