tags:

views:

109

answers:

4

Performance wise which one is better:

 $(".myclass").eq(0)

OR

 $("a.myclass")

Note: If there is only one <a> tag having .myclass.

+19  A: 

The second - always use tag names when you can (see rule 2 of the jQuery performance rules).

Dominic Rodger
+1 for the link about performance.
rahul
Thanks for the info :-)
Wondering
+6  A: 

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++.

Emil Ivanov
+1 - good explanation.
Dominic Rodger
+1  A: 

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...

cmcculloh
+1  A: 

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.

redsquare