What is the difference between the object returned by $('#elementID')
and the object returned by document.getElementById('elementID')
?
Moreover, how can you easily convert from one to the other? For instance:
$('a').each(function(){
// How can I access 'this' as a pure javascript object instead of as a jQuery object?
});
This has plagued me for some time now. I know you shouldn't mix the two, really, but I just want to understand the principle.
What will you use in jQuery if you wanted to convert the contents of a form element into string for submission? You can do this: var frm = $(document. myform); var data = JSON. stringify(frm.
Nevertheless, Native javascript is one of the best jQuery alternatives, in fact, It is the framework of JS. Javascript is the best because any browsers ships with javascript and you do not need to install jQuery in your application.
get()Returns: Array. Description: Retrieve the elements matched by the jQuery object.
A jQuery object is created from the array elements in the order they appeared in the array; unlike most other multi-element jQuery operations, the elements are not sorted in DOM order. Elements will be copied from the array as-is and won't be unwrapped if they're already jQuery collections.
What is the difference between the object returned by
$('#elementID')
and the object returned bydocument.getElementById('elementID')
?
$('#elementID')
returns an object with a ton of functions that all operate on the result of document.getElementById('elementID')
. Think of the jQuery object like a giant robot that document.getElementById('elementID')
is sitting inside of.
You can access the wrapped DOM object with:
$('#elementID').get()
$('#elementID').get(0)
$('#elementID')[0]
If there's more than one element matched by the selector, you can access, for example, the second element with $elements.get(1)
or $elements[1]
.
Moreover, how can you easily convert from one to the other?
To wrap an object with jQuery's convenience functions, just pass it into the $
function:
$(document.getElementById('foo'))
$(document.querySelectorAll('.foo:not(.bar)'))
To go the other way, use .get()
or the bracket notation.
In your specific example, you don't need to do anything special because this
is actually a normal DOM object. This is why you often see callbacks littered with $(this)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With