Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell jQuery to stop searching DOM when the first element is found?

Tags:

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?

like image 513
serg Avatar asked Oct 16 '10 21:10

serg


2 Answers

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.

like image 109
bobince Avatar answered Sep 17 '22 15:09

bobince


: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/

like image 29
Moin Zaman Avatar answered Sep 20 '22 15:09

Moin Zaman