Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a range of td cells with jquery

Say I have the following table

<table>
    <tr><td> #TD1 </td><td> #TD2 </td></tr>
    <tr><td> #TD3 </td><td> #TD4 </td></tr> 
    <tr><td> #TD5 </td><td> #TD6 </td></tr>
    <tr><td> #TD7 </td><td> #TD8 </td></tr>
    <tr><td> #TD9 </td><td> #TD10 </td></tr>
    <tr><td> #TD11 </td><td> #TD12 </td></tr>
    <tr><td> #TD13 </td><td> #TD14 </td></tr>
</table>

With jquery how do I select

  1. #TD5, #TD7 and #TD9 ?
  2. #TD6, #TD8 and #TD10 ?

I'm interested in an adaptable solution as my table might vary in columns and rows and I might need to select 4 rows going down rather than just three.

So far I've got

 $("table tr:gt(1) td:nth-child(1)").css('color','red')

but it doesnt stop at #TD11

See also http://jsfiddle.net/2ygJk/

like image 935
32423hjh32423 Avatar asked Sep 06 '25 03:09

32423hjh32423


2 Answers

Try:

$("table tr:gt(1):lt(3)").css('color','red')

http://jsfiddle.net/2ygJk/4/

like image 74
KingKongFrog Avatar answered Sep 07 '25 23:09

KingKongFrog


jQuery Filter is your friend

var indexes = [5,7,9]; // the indexes you would like to filter out

var filterdCelles = $('td').filter(function(i){
    return indexes.indexOf(i) > -1;
})

And then you can just do:

filterdCelles.css('color','red'); // changes the font to this color
like image 24
vsync Avatar answered Sep 07 '25 23:09

vsync