> > I understand that you can take an ordinary DOM object and create a
> > jQuery reference out of it:
> >
> > var myDOMObject = document.myform.mytextfield; var myJQueryRef =
> > $(myDOMObject); var myHtml = myJQueryRef.html();
> >
> > I know, I can chain. But for the sake of this example, I won't.
> >
> > Is there a way to do the opposite? An imaginary method could be:
> >
> > var extractedDOMObject = myJQueryRef.extractObject(); var myHtml2 =
> > extractedDOMObject.innerHTML;
> >
> > What might be used to replace the imaginary extractObject() method?
> You want $.get(), which returns an array of DOM elements, or
> $.get(index) which returns a single element. If you want a
> single item, then $('#objectOfMyDesire').get(0) is your
> method of choice.
>
> Reference: http://docs.jquery.com/Core/get
.get(n) will certainly work, but there's a faster and shorter way to do it.
The jQuery object returned by $() is an array of DOM elements. It's not an
actual Array object - it doesn't have all the Array methods - but for
purposes of reading it, you can treat it just like an Array: It has a
.length property and [0], [1], ... elements.
So, instead of writing:
$('#objectOfMyDesire').get(0)
You can use:
$('#objectOfMyDesire')[0]
In fact, .get(n) simply uses the [n] indexing to return a value.
.get() with no arguments does a bit more. It makes a copy of the jQuery
object as an actual Array, with all of the methods that any other JavaScript
Array has (and doesn't have any jQuery methods, being an Array object, not a
jQuery object).
Here's the source code for .get():
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == undefined ?
// Return a 'clean' array
jQuery.makeArray( this ) :
// Return just the object
this[ num ];
},
-Mike