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

前端 未结 4 1525
臣服心动
臣服心动 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条回答
  •  -上瘾入骨i
    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)

提交回复
热议问题