The difference between document.getElementById() and jQuery()

Assuming we have a super simple markup like this:

1
<div id="foo"></div>

We just want to get the reference to the element. In classic JavaScript (vanilla JS) we used to do:

1
var foo = document.getElementById('foo');

And now, in the era of modern web development, we simply do:

1
var foo = $('#foo');

They’re equivalent, but they’re not identical. So what’s the actual difference between the two?

Well, let’s be honest: there’s not just one difference. These two functions will return a completely different object, so you can’t simply replace every getElementById() with $('#foo'). This will break your code.

The main difference is that the jQuery object is just a wrapper around the element.

Let’s see this difference a bit more in detail. Here we play with the console:

1
2
3
4
5
6
7
8
9
document.getElementById('foo')
>>> div#foo
$('#foo')
>>> [div#foo,
     context: document,
     selector: "#foo",
     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… including the div we want! In fact, if you call:

1
2
$('#foo')[0]
>>> div#foo

You get the right div and nothing more, just as you would if you were calling document.getElementById('foo').

Comments