JQuery.get () - Practical use?

I am trying to understand why you would use jQuery.get() and jQuery.get(index) . The docs say you need to convert the jQuery selection into a raw DOM object instead of working with the selection as a jQuery object and methods available to it.

So a quick example:

 $("div").get(0).innerHTML; 

matches with:

 $("div").html(); 

This is obviously a bad example, but I'm struggling to figure out when you will use .get() . Can you help me understand when I will use this method in my code?

+3
source share
7 answers

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 delete them, the jQuery get () method is really convenient. For example, in the code below, I save all my <li> elements on the page in an array, deleting them, and then adding them back to the page using this array. It makes sense?

 <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/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> 
+1
source

This happens often when you want to call your own JS method on an element.

 //submitting a form... $('#mySearchForm').get().submit(); 
+4
source

Sometimes you use 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 the prototype:

 $(element).whatever(); 
+4
source

This may come in handy when doing something like (psuedocode):

 a = $("div").get() ajaxsend(a) 

Sometimes you may need to pass the real DOM object to other functions that might not be able to handle the jQuery object.

+3
source

This is useful for accessing any JavaScript method that is not displayed through jQuery. For example, before jQuery offset () support, I would usually use get() as follows:

 var offTop = $(element).get(0).offsetTop; 

In another example, I used this recently to define the scrollHeight of an element.

 var scrollHeight = $(element).get(0).scrollHeight; 

It can also be written as:

 var scrollHeight = $(element)[0].scrollHeight; 
+2
source

Another possible use of get () is when you work with XML trees in jQuery.

0
source

I use it to get id for one element

  $(selector).get(0).id 
0
source

All Articles