document.getElementById vs jQuery $()
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]
.
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