Friday 24 August 2012

How to select a HTML table column using jQuery

Here is a method for selecting a column in a table using the selector :nth-child(n). You could then do whatever you want to it, like hiding or highlighting it. An example use could be showing that a particular column has been sorted, instead of the more tranditional method of showing some indicator on the header.
// Highlight column 2
$('table tr > td:nth-child(2), table tr > th:nth-child(2)')
    .attr('style', 'background-color:#CCF;');

// Hide column 3
$('table tr > td:nth-child(3), table tr > th:nth-child(3)')