How can I get jQuery to return a html element exactly the way that getElementById does?
if I console.log($('#container')) I will get :
[<div id="container"></div>]
But the API I am interacting with obviously doesn’t want that (an array) – it wants :
<div id="container"></div>
I know I can achieve this with $('#container').get(0) and a few other ways, It just seems overkill – especially as I’m selecting an ID which will always be unique.
What am I missing guys?
Thanks
If you just want a single DOM element, then just use plain javascript:
jQuery selectors always create a jQuery object with an array of elements in it. That’s just the way it’s designed. If you want a single element, you either get the first element out of the jQuery object or you use a different tool.
From a jQuery object, you can get the first object either with:
or with:
But, I would argue that both are more than you need if all you want is the single object that has an id. Just use
document.getElementById(). If you want less typing, you could make your own short function: