22

Suppose if I have multiple tables in my HTML page (without their 'id' attribute), so how can I select first row of the first table or any specific table using jQuery selectors?

6 Answers 6

34
$("table:first > tr:first")

or

$("table:first").find("tr:first")

or

$("table:first").children("tr:first")

or

$("table").eq(0).children("tr").eq(0)

So if I understand the followup question...

$("table:eq(1) tr:has(table:eq(2))")

translates to: get any tr's in the 2nd table's if the tr has a 3rd table

or

$("table").eq(1).children("tr:has(table:eq(2))")
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Chad, its working (only second option). But the next question is if I want to select any row of the second table in my page if it contains 3 tables. The command which you suggested is successful only for the first or the last table; what about the intermediate tables. Thanks
jQuery is really flexible and I would need to see your html structure to provide accurate examples. The first example in my code would not work if you had <tbody> <thead> tags in your table for example. Please post some sample HTML and I can whip up the selectors
I'd suggest swapping .children("tr:first") for .find('> tbody > tr, > tr') since some browsers add tbody to all tables and some don't
5

Something you can use to select the nth row in the nth table:

$("table:eq(n) tr:eq(n)")

with n being the zero based index of the table or tr.

Example:

$("table:eq(2) tr:eq(4)")

gets the 5th row of the 3rd table.

Comments

2

@svinto's answer is definitely the shortest, quickest and easiest way to accomplish this. If you're really concerned with performance (e.g. selecting within an arbitrary complex for loop), this might most likely prove to be a tad faster:

$('tr').eq(0)

If you need not use only jQuery selectors and actually require the DOM <TR> element, you can use:

$('table')[0].rows[0]

Alternatively:

$('tr')[0]

Comments

1

Using jQuery's eq() method you can specify the index of the element you want to get.
This will select the first row of the second table found in the DOM

$('table:eq(1) tr:first')

1 Comment

actually that will select the first row in the 3rd table. eq() is zero based
0

Although not jQuery specific, I was introduced to dom selectors at this w3c selectors page. It's very detailed but full of intricate examples.

1 Comment

and what the latest jQuery supports through their selector engine, Sizzle : wiki.github.com/jeresig/sizzle
0
$("tr:first");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.