What is the difference between the object returned by $('#elementID')
and the object returned by document.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)
.