14

how can you get a row by the index?

var rows = $('tr', tbl);
rows.index(0).addClass('my_class');
clarkk
  • 27,151
  • 72
  • 200
  • 340

9 Answers9

27

Use .eq().

var rows = $('tr', tbl);
rows.eq(0).addClass('my_class');

...or for your simple case, .first():

rows.first().addClass('my_class');
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
9

Using either the eq() function:

rows.eq(0).addClass('my_class');


Or the :eq() selector:

$('tr:eq(0)', tbl).addClass('my_class');
Town
  • 14,706
  • 3
  • 48
  • 72
4
var row=$('tr:eq(5)', tbl);  // returns the 5th row
Blindy
  • 65,249
  • 10
  • 91
  • 131
3

You could use the native rows[docs] property on the HTMLTableElement.

$(tbl[0].rows[0]).addClass('my_class');

As noted by @Felix, I've assumed that tbl is a jQuery object. If not, do this:

$(tbl.rows[0]).addClass('my_class');
Community
  • 1
  • 1
user113716
  • 318,772
  • 63
  • 451
  • 440
3

you can do

$('tr:eq(0)', tbl).addClass('my_class');

more on this http://api.jquery.com/eq-selector/

Amin Eshaq
  • 4,034
  • 1
  • 17
  • 21
3

You can use nth-child in your selector:

$('tr td:nth-child(3)').addClass('my_class');

Will get the third td.

2

Use eq()

$('tr', tbl).eq(0).addClass('my_class');
DanielB
  • 19,910
  • 2
  • 44
  • 50
0

For the first element (index 0) the answer provided to your earlier question should be fine.

For any nth element use eq selector

e.g:

var rows = $('tr:eq(8)', tbl);
Chandu
  • 81,493
  • 19
  • 133
  • 134
0

http://api.jquery.com/get/ says:

Retrieve the DOM elements matched by the jQuery object.
.get( [index] )
index A zero-based integer indicating which element to retrieve.

Note that you'll get the DOM object, not a jQuery one:

var rows = $('tr', tbl);
$(rows.get(0)).addClass('my_class');
Piskvor left the building
  • 91,498
  • 46
  • 177
  • 222