Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find column number of HTML table with jQuery

I want to find out the column number that a td belongs to using jQuery.

For example:

<table>
    <tr>
        <td>Row1, Column1</td>
        <td>Row1, Column2</td>
    </tr>
    <tr class="totalRow">
        <td>Row2, Column1</td>
        <td class="columnChild">Row2, Column2</td>
    </tr>
</table>

I want to find the column number for the cell with a class of columnChild. I know that it is the second child of .totalRow, and is the second column in the table, but how do I find this?

Eventually what I want to achieve is to add this to an array so I could have to columns with a class of columnChild and add these to the array, so I can then run a function for each row of a table on the second child.

I've tried writing this several times, but I'm hitting a bit of coders block so any help would be greatly appreciated. If you require any more info, let me know and I'll provide what I can.

like image 572
Antonio Moore Avatar asked Dec 21 '22 11:12

Antonio Moore


1 Answers

To get the index of the td in the tr, you can simply use

var index = $('.columnChild').index();

If you have several cells with this class and you want their index in an array (I'm not sure I understand the second question starting with "Eventually"), you can do

var indexes = $('.columnChild').map(function(){return $(this).index()});
like image 99
Denys Séguret Avatar answered Dec 27 '22 03:12

Denys Séguret