jQuery what is faster: selectors or methods?

后端 未结 4 471
-上瘾入骨i
-上瘾入骨i 2020-12-17 22:49

Let\'s say I have $(\'mySelector:first\'); and $(\'mySelector\').first();. Which way is the most efficient? I looked in the source, but still could

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-17 23:19

    The second would have to fetch ALL the items in the selector before getting the first. So the if the selector was 10,000 items it would fetch all 10,000 then the first from that group. I would hope the first would be better in this regard since it would filter as it searches (and stopping after the first was found). Probably trivial in most cases, though.

    Of course if you are chaining functions then it may be unavoidable:

    $('.someclass').addClass('otherClass').first().addClass('firstClass');
    

提交回复
热议问题