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
$("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))")
3 Comments
.children("tr:first") for .find('> tbody > tr, > tr') since some browsers add tbody to all tables and some don't@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
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
Although not jQuery specific, I was introduced to dom selectors at this w3c selectors page. It's very detailed but full of intricate examples.