How to highlight a column in html table on click using js or jquery?

前端 未结 4 408
日久生厌
日久生厌 2020-12-22 03:10

I am trying to implement a javascript which will highlight the column in an html table on click.As the below working example for row highlight i tried to use the same with t

4条回答
  •  Happy的楠姐
    2020-12-22 04:00

    You can use the following code:

    $('td').on('click', function() {
        var $currentTable = $(this).closest('table');
        var index = $(this).index();
        $currentTable.find('td').removeClass('selected');
        $currentTable.find('tr').each(function() {
            $(this).find('td').eq(index).addClass('selected');
        });
    });
    

    Just put this on your JS file and it will work on all available tables independently. In case you want to use it only on a specific table, just change the initial selector to $('#myTable td').

    Also dont forget to add the .selected{ background-color: #ace; } class in yor css file.

    Here is the working example.

    Cheers!

提交回复
热议问题