I'm new to jQuery, and I'm wondering what the difference is between jQuery's get()
and eq()
functions. I may misunderstand what the get()
function does, but I thought it odd that I couldn't call a function on the returned on the returned element in the same line.
//Doesn't work
I.e. $("h2").get(0).fadeIn("slow");
//Works
$("h2").eq(0).fadeIn("slow");
.get()
and.eq()
both return a single "element" from a jQuery object array, but they return the single element in different forms..eq()
returns it as a jQuery object, meaning the DOM element is wrapped in the jQuery wrapper, which means that it accepts jQuery functions..get()
returns an array of raw DOM elements. You may manipulate each of them by accessing its attributes and invoking its functions as you would on a raw DOM element. But it loses its identity as a jQuery-wrapped object, so a jQuery function like.fadeIn
won't work.Answers above have explained specificly and correctly. I want to add a few points here that might help for the use of
get()
.If you don't pass an argument to
.get()
, it will return an Array of the DOM elements.If you got a DOM object using
get()
, likevar s = $("#id").get(0)
you can turn it back into jQuery object simply by using this,$(s)
You can use
$obj[i]
as an alternative way if you don't want to use$obj.get(i)
, see below,get()
returns a DOM element whereas:eq()
andeq()
return a jQuery element. Since DOM elements have no methodfadeIn()
it fails.http://api.jquery.com/get/
http://api.jquery.com/eq-selector/
eq(i)
retrieves the ith member in the receiver's set as ajQuery
object, whileget(i)
returns the member at the ith position as a DOM element.The reason why this doesn't work:
Is because the
h2
DOM element doesn't have a method calledfadeIn
.You should use
eq(0)
here instead.I am giving an example that explains the points given by others here. consider the following code
and the corresponding js code,
This is what you will see
The first is a DOM object while the latter is a Jquery-wrapped object where you could call Jquery methods
To build on the other answers: