views:

69

answers:

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")
+1  A: 

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:

karim79
+3  A: 

$("#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
did not see the comments to the Q....but its here for clarification
redsquare
+1 - I just tested in FF and you're right.
karim79