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

前端 未结 4 1522
臣服心动
臣服心动 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:02

    As an ardent fan of code readability by humans I suggest neither approach is satisfying. .get(0) and [0] look too much like container indexing. More is at stake when converting a jQuery object to a DOM object. So I introduce a function to name what's going on.

    function dom_from_$($jquery_object) {
        var dom_object = $jquery_object.get(0);
        return dom_object;
    }
    

    Used like this:

    var domElement = dom_from_$($(selector));
    
    0 讨论(0)
  • 2021-02-19 03:03

    In the interest of speed I created a jsfiddle that loops over each 10,000,000 times. I created two tests with a form at the beginning of the document and the end with 1200 lines of dummy HTML between. Here are some preliminary results:

    Test1
    form at beginning with .get(0): 15981ms - faster
    form at beginning with [0]:     16089ms
    form at end with .get(0):       16554ms
    form at end with [0]:           15969ms - faster
    
    Test2
    form at beginning with .get(0): 14137ms
    form at beginning with [0]:     14034ms - faster
    form at end with .get(0):       13756ms - faster
    form at end with [0]:           14492ms
    
    Test3
    form at beginning with .get(0): 15952ms - faster
    form at beginning with [0]:     16810ms
    form at end with .get(0):       15905ms
    form at end with [0]:           15532ms - faster
    

    It looks like no significant difference in speed can be seen. However you would have to check in different browsers to be sure.

    You can check out the fiddle here: http://jsfiddle.net/AFfYx/ (takes about a minute to run)

    0 讨论(0)
  • 2021-02-19 03:07

    I have too low a rep to comment on ericbowden's answer, but here is a jsperf test comparing the two operations:

    http://jsperf.com/selector-get-0-vs-selector-0

    Consensus (on Chrome 32): Basically the same, very minor advantage towards [0]

    0 讨论(0)
  • 2021-02-19 03:19

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

    <span>1</span>
    <span>2</span>
    <span>3</span>
    

    $("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]);
    },
    
    0 讨论(0)
提交回复
热议问题