Skip to content Skip to sidebar Skip to footer

How To Find The Corresponding Th To A Given Td?

Basically the same question as How can I get the corresponding table header (th) from a table cell (td)? but not jQuery specific. From a given is there an easy way to fi

Solution 1:

Pure JavaScript's answer.

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) + ')')

As posted here in the more jQuery specifc question: https://stackoverflow.com/a/37312707/1524913

Solution 2:

HTML table model gives easier solution. jquery in this case is more sophisticated. I tested following table:

<tablestyle="width:100%"id="stock"><tbody><tr><td>foo</td><tdid="target">bar</td><td>-1</td><td>...</td></tr><tr><td>foo</td><tdid="target">bar</td><td>-1</td><td>...</td></tr></tbody><tr><td>foo</td><tdid="target">bar</td><tdcolspan="2">-1</td><!--<td>...</td>--></tr><thead><tr><th>Name</th><th>Type</th><th>Quantity</th><th>Options</th></tr></thead></table>

Script without jquery is simple and straightforward.

window.onload = function () {
        var tbl = document.getElementById('stock');
        var tds = document.getElementsByTagName('td');
        for (var i = 0, td; td = tds[i]; ++i) {
            td.onclick = function () {
                var tr = this.parentNode;
                console.log(tbl.rows[0].cells[this.cellIndex].innerHTML);
            }
        }
    }

jquery also is useful.

    $(document).ready(function () {
        $('#stock td').click(function () {

            console.log($(this).parents('table').find('tr:first-child').children('th:nth-child(' + (this.cellIndex + 1) + ')').html());
        });
    });

<thead> can be placed at the top, at the bottom, and between rows. thead inside tbody is obvious error but browser fixes it. Scripts work in any case.

Solution 3:

I think you need to step through the TH colSpans to exactly match the TD

Try

functiongetHeadCell(td) {
  var index = Array.prototype.indexOf.call(td.parentNode.children, td);

  var table = td;
  while (table && table.tagName != 'TABLE') table = table.parentNode;

  var cx = 0;
  for (var c = 0; cx <= index; c++) cx += table.rows[0].cells[c].colSpan;

  returntable.rows[0].cells[c - 1];
}

See https://jsfiddle.net/Abeeee/upt75s2x/34/ for a working example

Post a Comment for "How To Find The Corresponding Th To A Given Td?"