Is this:
var contents = document.getElementById('contents');
The same as this:
var contents = $('#contents');
Given that jQuery is loaded?
Is this:
var contents = document.getElementById('contents');
The same as this:
var contents = $('#contents');
Given that jQuery is loaded?
In case someone else hits this... Here's another difference:
If the id contains characters that are not supported by the HTML standard (see SO question here) then jQuery may not find it even if getElementById does.
This happened to me with an id containing "/" characters (ex: id="a/b/c"), using Chrome:
was able to find my element but:
did not.
Btw, the simple fix was to move that id to the name field. JQuery had no trouble finding the element using:
var contents = document.getElementById('contents');
var contents = $('#contents');
The code snippets are not the same. first one returns a
Element
object (source). The second one, jQuery equivalent will return a jQuery object containing a collection of either zero or one DOM element. (jQuery documentation). Internally jQuery usesdocument.getElementById()
for efficiency.In both the cases if more than one element found only the first element will be returned.
When checking the github project for jQuery I found following line snippets which seems to be using document.getElementById codes (https://github.com/jquery/jquery/blob/master/src/core/init.js line 68 onwards)
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()
oranimate()
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]
.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
or this
These will pull the element out of the jQuery object.
A note on the difference in speed. Attach the following snipet to an onclick call:
Alternate commenting one out and then comment the other out. In my tests,
On the other hand, the
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, technicallygetElementById
is quite a bit faster.Not exactly!!
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).