Reputation: 6349
I would like to know the difference between traversing and pseudo classes in jQuery selectors.
In a DOM that contains the following:
<ul id="destination">
<li>A</li>
<li>B</li>
</ul>
The following jQuery codes will select the same elements:
# Pseudo class
$("#destination li:first");
# Traversing
$("#destination").find("li").first();
I heard that the second way is more efficient, in spite of taking more keystroks. What is the best practice?
Upvotes: 2
Views: 247
Reputation: 268344
You can measure efficiency via your F12 Developer Tools. For instance, here's the output from the Profiler in Internet Explorer on both of these approaches using jQuery 2.1.2-pre.
Following is the result of using $.fn.find
and $.fn.first
. You'll note that it is considerably less work than using pseudo-classes.
As noted above, using pseudo-classes (non-standard Sizzle syntactic-sugar) requires a bit more work:
The results speak for themselves. Although these results are distinctly different, don't let this sway you one way or another. Use what is appropriate for your project. The actual performance differences would be negligible, and not likely worth your concern.
Upvotes: 2