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

前端 未结 3 1177
滥情空心
滥情空心 2020-12-29 04:28

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 eleme

3条回答
  •  太阳男子
    2020-12-29 04:54

    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.

提交回复
热议问题