document.getElementById vs jQuery $()
Asked Answered
A

13

691

Is this:

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

The same as this:

var contents = $('#contents');

Given that jQuery is loaded?

Adkins answered 1/11, 2010 at 14:53 Comment(4)
is this proven somewhere?Footie
@torazaburo Actually, jQuery version is not even 3 times slower (at least at latest Chrome). See: jsperf.com/getelementbyid-vs-jquery-id/44Enamelware
@MichałPerłakowski in that link the jquery version is 10 times slower. 26mil vs 2.4milMargaux
Correct updated link for JSPerf is: jsperf.com/getelementbyid-vs-jquery-id In my case (FF 58) it's 1000 times slower. Anyway, jQuery still performs 2.5 millions ops per second. In general that's not a problem, and it certainly cannot be compared in terms of functionality.Markusmarl
U
1153

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
Uncork answered 1/11, 2010 at 14:53 Comment(9)
For anyone interested document.getElementBy doesn't work correctly in <IE8. It also gets elements by name therefore you could theoretically argue document.getElementById is not only misleading, but can return incorrect values. I think @John new this, but I thought it wouldn't hurt to add it in.Storey
Take care if your identifier is not fixed. $('#'+id)[0] is not equal to document.getElementById(id) because id may contain characters which are treated special in jQuery!Heathenry
This was very helpful - never knew this! I'm sure I've actually used it before, though, which is what baffles me. Hey, you learn something every day! Thanks!Julissajulita
google jquery equivalent of document.getelementbyid and the first result is this post. thank you!!!Disprize
$('#contents')[0].id returns id name.Rondure
Is it possible to get jquery object from DOM object?Lurk
@EvrenYurtesen you can turn any DOM element into a jQuery Object. #626436Uncork
Usefull. I used it in side each() loop function. eg. $(this)[0]Latoshalatouche
For completeness, to get the DOM object you can use the get(...) method of a jQuery object, but is slower: 1 $( "#foo" ).get( 0 ); // Identical to $( "#foo" )[0], only slower. Source: learn.jquery.com/using-jquery-core/faq/…Jones
C
158

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

Commanding answered 1/11, 2010 at 14:56 Comment(6)
Do you happen to know which one is faster - $(document.getElementById('element')) vs $('#element')?Slumgullion
@IvanIvković: The first one is faster, since it doesn't involve string parsing.Commanding
@Commanding What is the main difference between raw DOM object and jQuery object? Just that using jQuery object we have ability to apply jQuery methods ?Electrode
@Roxy'Pro: They're different objects. jQuery objects wrap DOM objects. See the documentation.Commanding
This doc JavaScript DOM Objects vs. jQuery Objects looks useful. In one sentence, DOM objects are the objects that the web browser is using to render elements on the web page whereas jQuery objects are basically wrapper objects around a set of DOM elements.Retributive
This helped me, 13 years later. ThanksHyperspace
A
37

A note on the difference in speed. Attach the following snipet to an onclick call:

function myfunc()
{
    var timer = new Date();
    
        for(var i = 0; i < 10000; i++)
        {
            //document.getElementById('myID');
            $('#myID')[0];
        }
    

    console.log('timer: ' + (new Date() - timer));
}

Alternate commenting one out and then comment the other out. In my tests,

document.getElementbyId averaged about 35ms (fluctuating from 25ms up to 52ms on about 15 runs)

On the other hand, the

jQuery averaged about 200ms (ranging from 181ms to 222ms on about 15 runs).

From this simple test you can see that the jQuery took about 6 times as long.

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, technically getElementById is quite a bit faster.

Acantho answered 19/3, 2015 at 16:56 Comment(2)
Thank for this answer. I wanted to ask, should I replace all the $('#someID') with document.getElementById("someID") ? I am working on something in which I have extensively used $('#someID') and my page runs slow for big file inputs. Please suggest me what should be my move.Canterbury
If you are reusing the same one several times in the same scope then save it, like var $myId = $('#myId'); and reuse the saved variable $myId. Finding by id is generally a pretty fast thing though so if the page is sluggish there is probably a different reason.Acantho
G
35

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.

Gratulant answered 1/11, 2010 at 14:57 Comment(0)
H
17

No. The first returns a DOM element, or null, whereas the second always returns a jQuery object. The jQuery object will be empty if no element with the id of contents was matched.

The DOM element returned by document.getElementById('contents') allows you to do things such as change the .innerHTML (or .value) etc, however you'll need to use jQuery methods on the jQuery Object.

var contents = $('#contents').get(0);

Is more equivilent, however if no element with the id of contents is matched, document.getElementById('contents') will return null, but $('#contents').get(0) will return undefined.

One benefit on using the jQuery object is that you won't get any errors if no elements were returned, as an object is always returned. However you will get errors if you try to perform operations on the null returned by document.getElementById

Hair answered 1/11, 2010 at 14:57 Comment(0)
A
15

No, actually the same result would be:

$('#contents')[0] 

jQuery does not know how many results would be returned from the query. What you get back is a special jQuery object which is a collection of all the controls that matched the query.

Part of what makes jQuery so convenient is that MOST methods called on this object that look like they are meant for one control, are actually in a loop called on all the members int he collection

When you use the [0] syntax you take the first element from the inner collection. At this point you get a DOM object

Appomattox answered 1/11, 2010 at 14:56 Comment(0)
C
12

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:

var contents = document.getElementById('a/b/c');

was able to find my element but:

var contents = $('#a/b/c');

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 = $('.myclass[name='a/b/c']);
Countervail answered 18/9, 2012 at 16:21 Comment(0)
P
6

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 uses document.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)

// HANDLE: $(#id)
} else {
    elem = document.getElementById( match[2] );
Poppyhead answered 23/7, 2014 at 13:17 Comment(0)
H
5

Just like most people have said, the main difference is the fact that it is wrapped in a jQuery object with the jQuery call vs the raw DOM object using straight JavaScript. The jQuery object will be able to do other jQuery functions with it of course but, if you just need to do simple DOM manipulation like basic styling or basic event handling, the straight JavaScript method is always a tad bit faster than jQuery since you don't have to load in an external library of code built on JavaScript. It saves an extra step.

Hoodoo answered 1/11, 2010 at 15:1 Comment(0)
B
5

One other difference: getElementById returns the first match, while $('#...') returns a collection of matches - yes, the same ID can be repeated in an HTML doc.

Further, getElementId is called from the document, while $('#...') can be called from a selector. So, in the code below, document.getElementById('content') will return the entire body but $('form #content')[0] will return inside of the form.

<body id="content">
   <h1>Header!</h1>
   <form>
      <div id="content"> My Form </div>
   </form>
</body>

It might seem odd to use duplicate IDs, but if you are using something like Wordpress, a template or plugin might use the same id as you use in the content. The selectivity of jQuery could help you out there.

Bottom answered 8/2, 2014 at 14:44 Comment(0)
C
3

jQuery is built over JavaScript. This means that it's just javascript anyway.

document.getElementById()

The document.getElementById() method returns the element that has the ID attribute with the specified value and Returns null if no elements with the specified ID exists.An ID should be unique within a page.

Jquery $()

Calling jQuery() or $() with an id selector as its argument will return a jQuery object containing a collection of either zero or one DOM element.Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM.

Callous answered 3/1, 2019 at 20:19 Comment(0)
G
3

All the answers are old today as of 2019 you can directly access id keyed filds in javascript simply try it

<p id="mytext"></p>
<script>mytext.innerText = 'Yes that works!'</script>

Online Demo! - https://codepen.io/frank-dspeed/pen/mdywbre

Gurgle answered 24/12, 2019 at 7:58 Comment(0)
C
2

All the answers above are correct. In case you want to see it in action, don't forget you have Console in a browser where you can see the actual result crystal clear :

I have an HTML :

<div id="contents"></div>

Go to console (cntrl+shift+c) and use these commands to see your result clearly

document.getElementById('contents')
>>> div#contents

$('#contents')
>>> [div#contents,
 context: document,
 selector: "#contents",
 jquery: "1.10.1",
 constructor: function,
 init: function …]

As we can see, in the first case we got the tag itself (that is, strictly speaking, an HTMLDivElement object). In the latter we actually don’t have a plain object, but an array of objects. And as mentioned by other answers above, you can use the following command:

$('#contents')[0]
>>> div#contents
Canterbury answered 11/3, 2019 at 7:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.