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

前端 未结 3 1171
滥情空心
滥情空心 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 05:00

    I'm not an expert on jQuery's innards, but my understanding is that the order in which jQuery may find things isn't necessarily the order they appear in the DOM. In order to ensure that you do get the item that is first in the DOM, jQuery gets everything and sorts the result so that the first element is returned.

    As you've noticed, this is a performance issue. However, I don't believe you can turn this behaviour off.

    What you can do is make your queries more specific, so that less gets selected and there are less elements for jQuery to sort in order to find the first one. For example, $('li:first') isn't very specific and will be slow. $('#myList>li:first') will in theory be a lot faster (though I've not benchmarked it to check) because a) it will only search in a single list, and b) sublists will also be excluded.

    If you will be using all the items in a selection for something at some point, but only need the first one at a particular point, then it makes sense to run the selector to get all your elements and save it to a var, then use .first() to get the first element when you need it.

    var elems = $('li'), firstElem = elems.first ();
    

    Now elems will hold the full set, and firstElem will hold just the first element.

    Of course, you could also just give the first element in each group you intend to select a specific class, but this might be considered an inelegant solution.

提交回复
热议问题