I have read how to best tune jQuery selectors. I just have a doubt on a point for which I have not found a reference on SO.
Given div.my-class and .my-class represent the same thing in the DOM (ie all tags with .my-class are divs) is it generally faster to do:
A brief explanation about the underlying reason would be great. Is the performance impact significant? The example on jQuery site shows
.find('div.my-class') but maybe that is just an example.
EDIT: having run a jsPerf it seems $('#my-id').find('.my-class') is a bit faster. Probably find('div.my-class') performs a small extra task. The point of this question is to obtain a good practice orientation when dealing with the find method and specificity. I will leave this open for a while to see if someone has the underlying reason for the results we had with jsPerf. Thanks to @dnozay for the additional tests.
Best How To :
Don't trust anyone without benchmarks to prove it.
With this prep code:
<span class="my-class"></span><!-- should not be matched? -->
The first testcase:
is 3x slower on my browser than:
However they don't return the same elements. So it depends on what your html looks like.
This query is trying to check all aspects at once:
This query is cutting elements out early by matching an id:
This query is going one step further to match the class first, then match the tag.
If you have seen http://jsperf.com/275308711/, then check http://jsperf.com/275308711/2, which adds another testcase.