Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
147
rated 0 times [  148] [ 1]  / answers: 1 / hits: 35453  / 12 Years ago, thu, january 24, 2013, 12:00:00

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.


More From » jquery

 Answers
6

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

[#80642] Wednesday, January 23, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
breonnamayah

Total Points: 574
Total Questions: 115
Total Answers: 96

Location: England
Member since Sun, May 21, 2023
1 Year ago
;