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.- Both methods return the same result if the
$(selector)is empty (undefined) - The jQuery documentation on
.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. - Also, you can call
.get()with no arguments to return all the DOM elements of the jQuery array.
.getallows you to use negative indices. For example:$("span").get(-1);refers to the thirdspan.But if you don’t need that feature and only want to select one element
.get(0)and[0]are the same. Notice thethis[num]: