document.getElementById vs jQuery $()
Solution 1:
Not exactly!!
document.getElementById('contents'); //returns a HTML DOM Object
var contents = $('#contents'); //returns a jQuery Object
In jQuery, to get the same result as document.getElementById
, you can access the jQuery Object and get the first element in the object (Remember JavaScript objects act similar to associative arrays).
var contents = $('#contents')[0]; //returns a HTML DOM Object
Solution 2:
No.
Calling document.getElementById('id')
will return a raw DOM object.
Calling $('#id')
will return a jQuery object that wraps the DOM object and provides jQuery methods.
Thus, you can only call jQuery methods like css()
or animate()
on the $()
call.
You can also write $(document.getElementById('id'))
, which will return a jQuery object and is equivalent to $('#id')
.
You can get the underlying DOM object from a jQuery object by writing $('#id')[0]
.
Solution 3:
Close, but not the same. They're getting the same element, but the jQuery version is wrapped in a jQuery object.
The equivalent would be this
var contents = $('#contents').get(0);
or this
var contents = $('#contents')[0];
These will pull the element out of the jQuery object.
Solution 4:
A note on the difference in speed. Attach the following snipet to an onclick call:
function myfunc()
{
var timer = new Date();
for(var i = 0; i < 10000; i++)
{
//document.getElementById('myID');
$('#myID')[0];
}
console.log('timer: ' + (new Date() - timer));
}
Alternate commenting one out and then comment the other out. In my tests,
document.getElementbyId averaged about 35ms (fluctuating from
25ms
up to52ms
on about15 runs
)
On the other hand, the
jQuery averaged about 200ms (ranging from
181ms
to222ms
on about15 runs
).From this simple test you can see that the jQuery took about 6 times as long.
Of course, that is over 10000
iterations so in a simpler situation I would probably use the jQuery for ease of use and all of the other cool things like .animate
and .fadeTo
. But yes, technically getElementById
is quite a bit faster.