Reputation: 37068
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.
Upvotes: 13
Views: 13562
Reputation: 298196
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)
.
Upvotes: 30
Reputation: 642
I have used the following code for creating a simple javascript element array but some cases i found i need to use the same element as jQuery object. then i found following solution to do it.
var cboxes = document.getElementsByName('deletecheck');
var len = cboxes.length;
for (var i=0; i<len; i++) {
if (cboxes[i].checked){
jQuery(cboxes[i]).parent().parent().remove();
}
}
Upvotes: 0
Reputation: 3856
Jquery objects contain both properties that describe the object and methods(functions) to interact with that object
Upvotes: 0
Reputation: 4140
A jquery object is just an array with special functions
// non-jquery -> jquery
var a = document.getElementById('some-link'); // one element
var $a = $(a);
// jquery -> non-jquery
a = $a[0]; // a jquery element holds all of its matches in the indices 0..(a.length) just like a JS array
Upvotes: 7