From what I understand, adding .first()
or :first
to a query doesn't stop DOM search after the first match. It just tells jQuery to take 1st element out of matched collection.
If that is true, then is there a way to stop DOM search after the first match? For example, if I know that the result of this query will always be a single element, how can jQuery be told to not waste time searching further?
As far as I know there's no way to do this in jQuery at the moment. The best you can do is $(selector).first()
, where selector
is a standard CSS selector not including any Sizzle-specific selectors (so don't use :first
). In this case jQuery uses the fast DOM querySelectorAll
method in modern browsers.
You can get the optimisation manually by using the DOM querySelector
method which is built to select only the first match:
$.getFirst= function(selector) { if ('querySelector' in document) return $(document.querySelector(selector)); else return $(selector).first(); }
however the amount you'll save by doing this is much smaller than the amount you save by making sure querySelectorAll
can be used.
:first
matches only a single element. its equivalent to :eq(0)
.
.first()
reduces the set of matched elements to the first in the set.
so using :first
would seem like its what you need, but on looking closer they're both using selectors first to find a set and then going on to use the first.
There's some comments and discussion here and here that seems to indicate that :first()
doesn't stop at the first element.
References:
http://api.jquery.com/first-selector/
http://api.jquery.com/first/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With