Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - get elements in a specified columns of an html table

Tags:

html

jquery

Using jquery, I'd like to get all elements in a specified columns of an html table. Please note that it can be more than one column

For example, if I have the following html table:

<table>
   <tr> 
    <td>
      a
    </td>
    <td>
      b
    </td>
    <td>
      c
    </td>
   </tr>
   <tr> 
    <td>
      1
    </td>
    <td>
      2
    </td>
    <td>
      3
    </td>
   </tr>
</table>

which looks as following:

1     2      3
a     b      c

I would like to get 1, 3, a , c

How should I do it? What would be the most efficient way to do so? (I am traversing a huge table generated by some reporting utility)

like image 631
vondip Avatar asked Mar 29 '11 15:03

vondip


2 Answers

You can use the :nth-child() selector.

$("tr td:nth-child(1), tr td:nth-child(3)").css('color', 'red');
like image 84
Kaivosukeltaja Avatar answered Nov 08 '22 22:11

Kaivosukeltaja


Here is more or less generic example letting you define the desired indices as array:

var cellIndexMapping = { 0: true, 2: true };
var data = [];

$("#MyTable tr").each(function(rowIndex) {
    $(this).find("td").each(function(cellIndex) {
        if (cellIndexMapping[cellIndex])
            data.push($(this).text());
    });
});

$("#Console").html(data.join("<br />"));

Test case: http://jsfiddle.net/yahavbr/FuDh2/

Using associative array to have faster performance, as far as I know search for specific item in such array should be optimized already.

Note that in JS first index is always 0, so 1st and 3rd cells means indices 0 and 2.

like image 41
Shadow Wizard Hates Omicron Avatar answered Nov 08 '22 20:11

Shadow Wizard Hates Omicron