0

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

5
  • 2
    You can use $('#container')[0] Commented Jun 20, 2012 at 20:09
  • Why don't you just use getElementById? Commented Jun 20, 2012 at 20:10
  • In fact, I do not see a question here. You know more than you try to ask. Commented Jun 20, 2012 at 20:11
  • I know it seems an odd question! I am currently using getElem... but I have a few HTML nodes I'm accessing and just wondered if I could cut down on typing! haha! Commented Jun 20, 2012 at 20:18
  • 1
    To cut down on typing, define your own shortcut replacement function for document.getElementByid() like I've shown in my answer below. Commented Jun 20, 2012 at 20:19

2 Answers 2

5

If you just want a single DOM element, then just use plain javascript:

var obj = document.getElementById("container");

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:

$('#container').get(0)

or with:

$('#container')[0]

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:

function $$(id) {
    return(document.getElementById(id));
}

var obj = $$("container");
Sign up to request clarification or add additional context in comments.

6 Comments

just a thing, should be "container" not "#container"
@Rodolfo - yes, I fixed the typo.
You should drop the # it will not work with plain javascript.
Thanks man. You answered my question with jQuery selectors always create a jQuery object with an array of elements in it - I was wondering if it could return a single element, to help me cut down on characters. :p
@user1036214 - Did you see the last part of my answer that makes for less typing?
|
0

try using .html() it will return the html of the element your selecting see:

http://api.jquery.com/html/

1 Comment

That will return the contents of the element, not the element itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.