vulkoingim vulkoingim - 1 year ago 96
jQuery Question

jQuery get table header name of clicked cell with id

I have a table, and in that table I have values with

. Now, what I want is to get the header name of the corresponding column when I click on any of the cells. What I have so far, based on a previous question asked is:

$('body').on('click', 'td#edit', function() {
var th = $('this').closest('th').eq($('th').val());
alert(th); // returns [object Object]

Can you help me out with this?


<table id="myTable" class="myTable">
<td class="check">
<input type="checkbox" value="12345">
<td class="edit">
<td class="edit">gdsgasdfasfasdfa</td>
<td class="edit">2011-01-21</td>
<td class="edit">TRUE</td>
<td class="edit">RP</td>
<td class="edit">FALSE</td>
<td class="edit">0</td>
<td class="edit">5152342</td>
<td class="edit">66665464</td>

Answer Source

The function closest() loop in ancestors up the DOM tree and th is not parent of td so closest is not right option. First of all use class if you are having same id for more than one elements. Secondly use index() to find the corresponding th of td. For being specific assign id to parent table so that the script does not operate on other tables / td on page.

Live Demo


<table id="tbl1" border="1">
        <th>heading 1</th>
        <th>heading 2</th>
        <td class="edit">row 1, cell 1</td>
        <td class="edit">row 1, cell 2</td>
        <td class="edit">row 2, cell 1</td>
        <td class="edit">row 2, cell 2</td>


$('#tbl1').on('click', '.edit', function () {
    var th = $('#tbl1 th').eq($(this).index());
    alert(th.text()); // returns text of respective header
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download