tags:

views:

27

answers:

2
+1  Q: 

highlight a column

I saw in one of the jQuery books where you can highlight a column that's being sorted.

$('th.sortable').click(function() {
    var $th = $(this);
    var column = $th.index();
    var $table = $th.closest('table');
    var rows = $table.find('tr:not(:has(th))').get();

Q: How do I add the 'hightlight' class to every cell in the column that was clicked?

+3  A: 

There is a nth-child selector which you can use in this case.

$('th.sortable').click(function() {
    var $th = $(this),
        column = $th.index(),
        $table = $th.closest('table');

    $table.find('tr td:nth-child(' + (column+1) + ')').addClass('highlight');
});
Harmen
note that _index_ is zero-based and _nth-child_ is 1-based.
Nikita Rybak
You're right, I've updated it.
Harmen
+3  A: 

I'd think you'd be able to do something like this:

Example: http://jsfiddle.net/4Sg8E/

$('th.sortable').click(function() {
    var $th = $(this);
    $th.closest('table').find('td:nth-child(' + ($th.index() + 1) + ')')
        .css('background','yellow');
});

It will get all <td> elements that are the same position as the <th> that was clicked, and hilight them.

patrick dw
You mean `column+1` I think, as you just told me `.index()` was zero-based, while `nth-child` is 1-based. index=0 -> nth-child(1)
Harmen
@Harman - Someone else told you index is zero based, and yep, I had it backwards. Already updated.
patrick dw