document.getElementById vs jQuery $() document.getElementById vs jQuery $() javascript javascript

document.getElementById vs jQuery $()


Not exactly!!

document.getElementById('contents'); //returns a HTML DOM Objectvar 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


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].


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.