jQuery and Table, grab every cell in the NTH colum

2020-02-25 07:54发布

Lets say I have your basic table layout (like below). How to I grab every NTH cell? I basically want to add a css class to the cells in column N.

So if I wanted all cells in column 2, I want to have a jQuery obj that contain the following cells that are marked:

<table>
    <tr class="trow">
        <td></td>
        <td></td> <!-- included -->
        <td></td>
    </tr>
    <tr class="trow">
        <td></td>
        <td></td> <!-- included -->
        <td></td>
    </tr>
    <tr class="trow">
        <td></td>
        <td></td> <!-- included -->
        <td></td>
    </tr>
</table>

标签: jquery
3条回答
再贱就再见
2楼-- · 2020-02-25 08:14

nth Selector

$('table>tbody>tr>td:nth-child(2)').addClass('someClass');
查看更多
▲ chillily
3楼-- · 2020-02-25 08:27

Try the jQuery nth Cell selector... Must be there!

$("table tr td:nth-child(n)").addClass("MyGreatClass");
查看更多
聊天终结者
4楼-- · 2020-02-25 08:32

There are many ways to do this. The best way depends on how the table is generated and what you will be doing with the cells in javascript/JQuery.

You could add an id to each cell, something like "cell-row-col". This allows you to grab any cell via document.getElementByID().

查看更多
登录 后发表回答