Growing with the Web

How to select a HTML table column using jQuery

Published
Tags:

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 traditional 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)')
    .hide();

Comments

comments powered by Disqus
Like this article?
Subscribe for more!