I am trying to understand why you would use jQuery.get()
and jQuery.get(index)
. The docs say it is to convert the jQuery selection to the raw DOM object instead of working with the selection as a jQuery object and the methods available to it.
So a quick example:
$("div").get(0).innerHTML;
is the same as:
$("div").html();
Obviously this is a bad example but I am struggling to figure when you would use .get()
. Can you help me understand when I would use this method in my code?
I am trying to understand why you would use jQuery.get()
and jQuery.get(index)
. The docs say it is to convert the jQuery selection to the raw DOM object instead of working with the selection as a jQuery object and the methods available to it.
So a quick example:
$("div").get(0).innerHTML;
is the same as:
$("div").html();
Obviously this is a bad example but I am struggling to figure when you would use .get()
. Can you help me understand when I would use this method in my code?
7 Answers
Reset to default 4It happens often when you want to call a native JS method on an element.
//submitting a form...
$('#mySearchForm').get().submit();
Sometimes you're using jQuery in noConflict mode and you want to do something like:
var element = jQuery('#jquery_selectors .are > .awesome[and=fast]').get(0);
And then do something in prototype:
$(element).whatever();
This may e in handy when doing something like (psuedocode):
a = $("div").get()
ajaxsend(a)
There are times when you may need to pass the actual DOM object to other functions, which may not be able to handle the jQuery object.
This is useful for accessing any JavaScript method that isn't exposed through jQuery. For example, before jQuery supported offset(), I would typically use get()
like this:
var offTop = $(element).get(0).offsetTop;
For another example, I used this recently to determine the scrollHeight of an element.
var scrollHeight = $(element).get(0).scrollHeight;
This can also be written as:
var scrollHeight = $(element)[0].scrollHeight;
Cody Lindley (jQuery Team Member) has a great example of why you would use get()
If you ever need to cache a set of elements, because you are about to remove them, the jQuery get() method is really handy. For example, in the code below I am saving all my
<li>
elements on the page in an array, removing them, and then adding them back into the page using this array. Make sense?
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis./ajax/libs/jquery/1.2.6/jquery.min.js"></script>
</head>
<body>
<ul>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
</ul>
<script>
var test = $('ul li').get();
$('ul').empty();
$.each(test, function(){ $('ul').append('<li>'+$(this).html() + ' new</li>'); });
</script>
</body>
</html>
Another possible use of get() is when you are working with XML trees in jQuery.
I use it to get id for single element
$(selector).get(0).id