2

A couple of questions actually,

Given that the following two will return the same result set

$("#MyTable tr");
$("tr", "#MyTable");

is there any difference in performance between using the Parent-Child CSS selector convention or specifying a context to the selector instead?

Also, given that I can guarantee a tr will be an immediate child of a table, would this improve upon the performance of the above?

$("#MyTable>tr")
Thinker
  • 14,234
  • 9
  • 40
  • 55
James Wiseman
  • 29,946
  • 17
  • 95
  • 158
  • 4
    "given that I can guarantee a tr will be an immediate child of a table" - don't bet on it. Browsers should (except in XHTML mode) imply a tbody element between tables and table rows. – Quentin Aug 19 '09 at 10:33
  • @David Dorward - Fair comment. Although if we can't make this basic assumptions, does that not render this selector, and the .children() function redundant? – James Wiseman Aug 19 '09 at 10:43
  • No. It just means you need to be careful when dealing with elements with implicit start tags. The only one that people routinely fail to include the start tag is tbody, just be explicit about it being there and you can stop worrying. – Quentin Aug 19 '09 at 13:25

2 Answers2

3

$("#MyTable > tr") may not actually work as you should have either thead/tfoot or tbody as the direct child of the table. I think ff/chrome etc will add the tbody in for you therefore the selector should be

$("#MyTable > tbody > tr")
redsquare
  • 78,161
  • 20
  • 151
  • 159
1

By far, the fastest of those three is:

$("#MyTable > tr")

as you are selecting a direct descendant of an element reference by an id, so the selection is pretty direct.

EDIT: @redsquare has pointed out that the above will not work in Firefox and Chrome as those browsers will append a tbody element to tables.

Context selectors are basically converted into 'finds', so the slowest of the first two is:

$("tr", "#MyTable");

as it is converted into something like this before any selection takes place:

$('#MyTable').find('tr');

Of course, it would probably be of great benefit to you to benchmark those yourself.

Here are some related questions previously asked on SO:

Community
  • 1
  • 1
karim79
  • 339,989
  • 67
  • 413
  • 406