views:

2629

answers:

6

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?

+5  A: 
$("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))")
Chad Grant
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
Chad Grant
A: 

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

Josh
and what the latest jQuery supports through their selector engine, Sizzle : http://wiki.github.com/jeresig/sizzle
Chad Grant
+1  A: 

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')
duckyflip
actually that will select the first row in the 3rd table. eq() is zero based
Chad Grant
You're right Chad I tottaly forgot about this, fixed.
duckyflip
A: 
$("tr:first");
svinto
+1  A: 

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.

Thomas Stock
A: 

@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]
Wynand