I was wondering the other day when typing you selectors in jQuery would it make a difference in performance if you specify your selectors very specific or very loosely.
'#myid .myclass'
1) find all elements that have the class myclass
2) for each such element, go up its ancestor chain and stop if you get to the #myid
ancestor. If there is no such ancestor, discard the element.
Now, it could very well be that browsers optimize this process, for example:
1) find the #myid
element
2) find all elements that have the class myclass
and that are descendants of the #myid
element
table#myid > tbody > tr > td > div.mylcass
Note that prefixing the ID selector with a type selector has no effect, since IDs are unique in the document.
#myid > tbody > tr > td > div.mylcass
Prefixing a class selector with a type selector is performance-wise better. So, if you know the type of the element, you are encouraged to set it.
I'm not sure about those child selectors. I guess it should be faster if you use them. But how much faster? Possibly neglectable? Also, It looks ugly.
Consider this:
#myid td > div.myclass
If #myid
is a table element, and you have no nested tables, then this selector should be as fast as your second selector. I'd use this one.