MyDaftQuestions MyDaftQuestions - 4 months ago 13
Javascript Question

Why does jquery UI draggable not work with getElementById

I thought the 2 were the same.

$("#SomeId")


and

document.getElementById("SomeId")


I assume I am wrong because the following works

$("#SomeId").draggable();


Where as neither of these do

document.getElementById("SomeId").draggable();


or

var x = document.getElementById("SomeId");
x.draggable();


My question is what is the difference here? Is JQuery doing some trickery and registering in such a way that only elements chosen via JQuery can work with JqueryUI?

So far my project has been only vanilla Javascript but now I must use JQuery and so I'm migrating. I know how to work around this and have a few ideas for fixes but my question is about why this doesn't work as understanding is more important.

Answer Source

This doesn't work because the jquery selector gets more than just the element. It returns a jquery object, allowing you to do jquery-ee stuff to them, like .draggable().

If you want to use the javascript getElementById() method, you can make it work if you were to change your example above to:

var x = document.getElementById("SomeId");
$(x).draggable();

Which will turn the plain javascript object into a jquery object.

If you console.log() both the jquery object, and the js dom object separately, you'll see they are very different.