Why use jQuery(selector).get(0) instead of jQuery(selector)[0] to get DOM element?

前端 未结 4 1523
臣服心动
臣服心动 2021-02-19 02:34

Using jQuery is there any benefit to using $(selector).get(0) over $(selector)[0] if I just want to get the first item in the jQuery array as a DOM ele

4条回答
  •  野的像风
    2021-02-19 03:19

    .get allows you to use negative indices. For example:

    1
    2
    3
    

    $("span").get(-1); refers to the third span.

    But if you don't need that feature and only want to select one element .get(0) and [0] are the same. Notice the this[num]:

    // jQuery code
    get: function (num) {
        return num == null ?
    
        // Return a 'clean' array
        this.toArray() :
    
        // Return just the object
        (num < 0 ? this[this.length + num] : this[num]);
    },
    

提交回复
热议问题