40

I want to select a table column and all I know is the header text of the column. (th.innerText)

I tried the following code but it doesn't work:

ownerIndex = $('th:contains("Owner")').index();
$('table tr td:nth-child(ownerIndex)')

any ideas?

5 Answers 5

67

Ok. I found a solution:

$('table tr td:nth-child('+ownerIndex+')')
3
  • 9
    This works if every cell has colspan=1, but breaks if cells have different column spans. Commented Mar 11, 2013 at 21:45
  • Thanks, I have added to your idea in order to set columns widths for "table-layout:fixed" style. In this case I select children from colgroup eg. $('#plGrid colgroup col:nth-child(0)').css('width', '150px'); $('#plGrid colgroup col:nth-child(1)').css('width', '250px'); Commented Apr 28, 2015 at 17:08
  • make that nth-child(1); nth-child(2) Commented Apr 28, 2015 at 18:36
28

In the example above ownerIndex needs to be incremented by 1 to match the indexing of nth-child, which starts at 1 rather than 0.

Here's my take: http://jsfiddle.net/2xU8t/

/* Set all the cells in columns with THEHEADING in the heading to red */

// Find the heading with the text THEHEADING
columnTh = $("table th:contains('THEHEADING')");

// Get the index & increment by 1 to match nth-child indexing
columnIndex = columnTh.index() + 1; 

// Set all the elements with that index in a tr red
$('table tr td:nth-child(' + columnIndex + ')').css("color", "#F00");

// Set the heading red too!
columnTh.css("color", "#F00"); 
1
  • This is the only answer that's actually correct. The others, including the one with the most votes, miss the fact that .index() will return a zero-based index (i.e. the first column's index is 0), whereas :nth-child takes an argument which is 1-based (i.e. the first column will be :nth-child(1). Commented Apr 13, 2021 at 16:15
3

This seems to work using the back tick as opposed to a single quote:

$(`table tr td:nth-child(${ownerIndex})`)
0

the examples above do not work me, because my cell don't have same cosplan, and i found this solution:

 $("table tr>td:nth-child(${ownerIndex})");
0

I tried

$("table tbody tr td:eq(4)")

on mine to only get one result..

Oddly enough, find TRs first, then find td:eq(col) worked correctly..

$("table tbody tr").find("td:eq(4)")

For colspan issues, I recommend adding a class to handle it correctly..

<td class="CALC" colspan=2>

$("table .CALC")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.