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 element?
HTML:
<form id="myForm"></form>
Javascript:
var selector = '#myForm';
var domElement = $(selector).get(0); //Returns [object HTMLFormElement]
//Or
var domElement = $(selector)[0]; //Also returns [object HTMLFormElement]
.get()
is more characters to type.$(selector)
is empty (undefined
).get()
notes that you can simply use the index accessor to get the nth element, but you don't get the other benefits of .get()
such as using a negative number to return items from the end of the array..get()
with no arguments to return all the DOM elements of the jQuery array.Pure JavaScript can be faster for DOM selection/manipulation than jQuery as JavaScript is directly processed by the browser. jQuery has to be converted into JavaScript to make it run in a browser. All these can be done in JavaScript but we may have to write many lines of code.
jQuery is a wrapper that normalizes DOM manipulation in a way that works consistently in every major browser. It's fully reasonable for it to perform 25x slower than direct DOM manipulation. The performance loss is a tradeoff to have concise code.
The Document Object Model (DOM) elements are something like a DIV, HTML, BODY element on the HTML page. A jQuery Selector is used to select one or more HTML elements using jQuery. Mostly we use Selectors for accessing the DOM elements.
At the moment the script is executed, the element does not exist yet and getElementById will return null . The same applies to all selectors with jQuery. jQuery won't find elements if you misspelled your selector or you are trying to select them before they actually exist.
.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]);
},
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With