jQuery :first vs. .first()

前端 未结 4 1733
夕颜
夕颜 2020-11-29 01:12

The .first() method was added in jQuery 1.4.

The :first selector has been around since 1.0.

From the docs:

:first

4条回答
  •  清歌不尽
    2020-11-29 02:09

    If .first() and :first are used in the same context to get the same information, example:

    Html:

    • One
    • Two
    • Three
    • Four
    • Five

    Script:

    console.log("1", $('ul li').first().text());
    console.log("2", $('ul li:first').text());
    

    .first() is more performant

    ** enter image description here

    As mentionned by Andrew Moore, .first() is the equivalent of .eq(0).
    According to jsperf.com, .eq(0) would be the best, but there is no big difference with .first().

    You can see my source, here: http://jsperf.com/first-vs-first-vs-eq-0

提交回复
热议问题