document.getElementById vs jQuery $()

Is this:

var contents = document.getElementById('contents');

The same as this:

var contents = $('#contents');

Given that jQuery is loaded?


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

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.

链接地址: http://www.djcxy.com/p/15460.html

上一篇: 名称与ID

下一篇: document.getElementById vs jQuery $()