Assuming we have a super simple markup like this:
And now, in the era of modern web development, we simply do:
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
$('#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:
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:
You get the right div and nothing more, just as you would if you were calling