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)
You can use the :nth-child()
selector.
$("tr td:nth-child(1), tr td:nth-child(3)").css('color', 'red');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With