It depends on your selector. Unless you use a special jquery selector or selector, such as .someclass
, #someid
or div
, jquery passes the selector directly to element.querySelectorAll()
, which uses a browser selector to do the job. Therefore, jquery does not iterate over all elements, that is, there is no way to make it βstopβ when it finds the first one, it will find them all and then give you all. Instead, you can use element.querySelector()
and skip jQuery so that the browser returns only the first match, but whether it is significantly faster will depend on how the browser implements these methods. (it will always be slightly faster simply because it does not use jQuery, but looking at jsperf, it seems that it is faster to use querySelector
instead of querySelectorAll
)
Now, when it comes to selectors that only have a jQuery selector, just omit these jquery selectors only from your .find
and instead use them in .filter
so you use the more efficient element.querySelectorAll()
first, then filter only the results only using jQuery selector.
For example, .find(".foo:button")
will be more efficiently written as .find(".foo").filter(":button")
https://developer.mozilla.org/en-US/docs/Web/API/element.querySelector
http://jsperf.com/queryselectorall-vs-getelementbyid/35
jQuery is not used in jsperf, but since the way you select jQuery elements is highly dependent on the same methods used in jsperf, I think it matters. Choosing a jQuery selector by identifier and choosing by class, for example, should see about the same performance difference as between getElementById
and getElementsByClassName
.
Besides,
At present, a function request is opened that will automatically make this switch for you: http://bugs.jquery.com/ticket/11785 he raised it because it does not appear to actually cause a significant increase in performance.