Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does specifying :first in jquery selector help performance?

If I know there is at most 1 such object in my DOM, should I always append :first to the selector to speed up the lookup? I'm assuming the selection engine will stop as soon as it finds 1 matching element, but I'm not sure if the filter actually slow things down a bit.

like image 489
Xerion Avatar asked May 18 '11 19:05

Xerion


People also ask

Which is the fastest selector in jQuery?

ID Selector: The jQuery #id selector selects the element on the basis of the ID attribute of the HTML tag. This selector is basically used when we have to work on a single element because an ID should be unique within a web page.

Which selector is faster in JavaScript?

ID and Element selector are the fastest selectors in jQuery.

Does jQuery improve performance?

Minimizing direct DOM manipulation improves jQuery performance. Every time an element is created and inserted, time and capacity is needed. Using a cached selector with the append() method reduces the need for capacity. The following example shows how applying DOM control improves performance.


1 Answers

No, as :first is not a standard CSS pseudo-class, and using it will cause your selector to not be passed to the native querySelectorAll() DOM function implemented by supporting browsers (assuming you don't use any other jQuery-only selector syntax).

jQuery will take the entire selector and parse it by itself (using Sizzle, most likely), which is leagues slower than letting the browser do the work.

like image 107
BoltClock Avatar answered Oct 29 '22 01:10

BoltClock