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
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));
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)
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]
.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]);
},