document.getElementById() in jQuery

The enduring popularity of this question on Stackoverflow: How to do this using jQuery – document.getElementById(“selectlist”).value took me back to the very first issue I had with jQuery. Namely:

Why on earth does $(“myid”) not give me the DOM object for “myid” like document.getElementById(“myid”)?

In fact it gives you a collection of all elements <myid> which for this is almost certain to be empty.

But no-one explains this to you. No-one takes you aside and says, “listen, forget the DOM, forget all its functions, pretend it never existed…this is all DIFFERENT”…or something.

This is the first thing you should know about jQuery. Everything else is trivial.

As I intimated in my answer $() and document.getElementbyId are “Equivalent”.

Being in the right place at the right time to answer this question was fortunate, and was the Stackoverflow equivalent of a Jackpot if you care about your reputation points. Here is the answer I gave, and how it looks after four revisions:

While…

$('#selectlist').val();

…is equivalent to…

document.getElementById("selectlist").value

…it’s worth noting that…

$('#selectlist')

…although ‘equivalent’ is not the same as…

document.getElementById("selectlist")

…as the former returns a jQuery object, not a DOM object.

To get the DOM object(s) from the jQuery one, use the following:

$('#selectlist').get(); //get all DOM objects in the jQuery collection
$('#selectlist').get(0); //get the DOM object in the jQuery collection at index 0
$('#selectlist')[0]; //get the DOM objects in the jQuery collection at index 0

It should also be noted that the return from $() is a collection, and may contain MANY items. If you are selecting by ID (using #) then you will only ever get one item

One thought on “document.getElementById() in jQuery

Leave a Reply