Reputation: 5096
Performance wise which one is better:
$(".myclass").eq(0)
OR
$("a.myclass")
Note: If there is only one <a>
tag having .myclass
.
Upvotes: 2
Views: 139
Reputation: 48623
For more, see Paul Irish's Anti-patterns starting at about slide 19.
Always descend from an ID if you can. Be more specific on the right and more general on the left.
There's a jquery based speed profiler out there that would allow you to test this to see the actual speed differences, but I'm having trouble finding it...
Upvotes: 1
Reputation: 78687
These things are easy to profile using firebug.
console.profile();
jQuery('#id');
console.profileEnd();
Sometimes it depends upon your dom / which browser your targetting etc etc rather than relying on 'best practise'. Always profile locally to see what works best.
Upvotes: 1
Reputation: 37673
The second, because it can use the browser's document.getElementsByTagName()
function that is implemented in C/C++, rather than Javascript.
Also, if there is only a single a
with .myclass
consider putting an id on it and doing $('#myid')
. Fetching by id is the fastest way. It uses document.getElementById()
which, again, is implemented in C/C++.
Upvotes: 6
Reputation: 99841
The second - always use tag names when you can (see rule 2 of the jQuery performance rules).
Upvotes: 19