Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimize jQuery selector with :first

I have had this feeling that $('.class:first') runs faster than $('.class'). So anytime I know there only is one .class in the subset, I've used it.

Does :first make the query run faster, or is it unnecessary?

like image 257
Znarkus Avatar asked Dec 10 '10 10:12

Znarkus


1 Answers

It actually depends on the browser, :first isn't a CSS selector, it's a jQuery filter - so that requires some extra parsing work...where as .class by itself can be handed off to a native browser selector method (e.g. document.querySelectorAll() here).

Any of these would actually be faster:

$('.class').first()
//or...
$('.class').eq(0)
//or fastest:
$('.class').slice(0, 1)

...since they run native code then just take the first entry in that set.

like image 139
Nick Craver Avatar answered Sep 27 '22 18:09

Nick Craver