How to find HTML table column number using jQuery

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

For instance:

<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 a cell with the columnChild class. I know this is the second child of .totalRow and the second column in the table, but how to find it?

In the end, I want to add this to the array so that I can have columns with the columnChild class and add them to the array, so I can run the function for each row of the table on the second child.

I tried writing this several times, but I find the bit of the encoder block, so any help would be greatly appreciated. If you guys need more information, let me know and I will provide everything I can.

+4
source share
2 answers

To get the td index in 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 "Ultimately"), you can do

 var indexes = $('.columnChild').map(function(){return $(this).index()}); 
+11
source

so I can run a function for each row of the table for the second child.

This will give you an array of td elements with class .columnChild (inside tr elements with class totalRow).

 $(".totalRow .columnChild") this will allow to iterate through the array $(".totalRow .columnChild") .each(function (index, element) { // element is the tr element // your function }); 

Hope this helps.

0
source

All Articles