Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.getElementById vs jQuery $()

Is this:

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

The same as this:

var contents = $('#contents'); 

Given that jQuery is loaded?

like image 858
Phillip Senn Avatar asked Nov 01 '10 14:11

Phillip Senn


People also ask

What is $() in jQuery?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.

Which is fast document getElementById (' txtName ') or #txtName ')?

The simple answer is document. getElementByID('txtName') is faster than $('#txtName') because jQuery is written on top of javascript. It means internally jQuery is using only native javascript codes.

What is the use of document getElementById?

The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

Can we use document getElementById in JS?

The getElementById() is a DOM method used to return the element that has the ID attribute with the specified value. This is one of the most common methods in the HTML DOM and is used almost every time we want to manipulate an element on our document. This method returns null if no elements with the specified ID exists.


1 Answers

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 
like image 186
13 revs Avatar answered Oct 05 '22 10:10

13 revs