Select column

I saw in one of jQuery books where you can highlight a sorted column.

$('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 to add a "hightlight" class to each cell in the column that was clicked?

+3
source share
2 answers

There is a selector nth-childthat 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');
});
+5
source

I would have thought you could 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');
});

He will receive all the elements <td>that are in the same position as clicking <th>, and will remove them.

+3
source

Source: https://habr.com/ru/post/1770396/


All Articles