14

how can you get a row by the index?

var rows = $('tr', tbl);
rows.index(0).addClass('my_class');
clarkk
  • 25,706
  • 67
  • 182
  • 315

9 Answers9

25

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
  • 344,413
  • 96
  • 627
  • 693
8

Using either the eq() function:

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


Or the :eq() selector:

$('tr:eq(0)', tbl).addClass('my_class');
Town
  • 14,391
  • 3
  • 48
  • 71
4
var row=$('tr:eq(5)', tbl);  // returns the 5th row
Blindy
  • 60,429
  • 9
  • 84
  • 123
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
  • 310,407
  • 61
  • 442
  • 435
3

you can do

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

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

Amin Eshaq
  • 4,024
  • 1
  • 16
  • 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,386
  • 2
  • 42
  • 49
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
  • 78,650
  • 19
  • 129
  • 131
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
  • 89,423
  • 44
  • 175
  • 222