0

I'm trying to simply reproduce what is on the jquery site for the .get method:

<!DOCTYPE html>
<html>
<head>
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 
</head>
<body>
    <ul>
        <li id="foo">foo</li>
        <li id="bar">bar</li>
    </ul>

<script type="text/javascript">
    alert($('li').get());
</script>
</body>
</html>

It should return

[<li id="foo">, <li id="bar">]

But all I get is [object HTMLLIElement],[object HTMLLIElement]

Does anybody know what I might be doing wrong here?

gdoron
  • 147,333
  • 58
  • 291
  • 367
Allen
  • 722
  • 4
  • 13
  • 31

4 Answers4

0

Simple, select the ul element and display it's content with the html function:

alert($('ul').html());

html docs:

Description: Get the HTML contents of the first element in the set of matched elements.

gdoron
  • 147,333
  • 58
  • 291
  • 367
0

Everything is alright:

The .get() method grants us access to the DOM nodes underlying each jQuery object.

Get returns the DOM elements hold by the jQuery variable. And when you output DomElements they become the form "HTMLLIElement".

knub
  • 3,892
  • 8
  • 38
  • 63
  • so is there a way to reproduce what they have here:hmm.. http://api.jquery.com/get/ – Allen Feb 08 '12 at 21:07
  • This IS what you get. Its just the output format, that differs. In fact, if you save your result, and check its length property afterwards, it will be 2. – knub Feb 08 '12 at 21:09
  • Ok..the answer is:var j = ($('li').get(0)); alert (j.innerHTML); – Allen Feb 08 '12 at 22:52
0

But that's what .get does! It will retrieve the HTML DOM elements matched by the selector. If you want the jQuery objects, you should use just $('li').

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
0

You're not necessarily doing anything wrong.

What you're getting is the actual result of calling toString (which alert will do for you) on an array with 2 <li> DOM objects in it:

[object HTMLLIElement],[object HTMLLIElement]

However, what's mentioned in the API Documents isn't a string representation of the array, but is meant as a description of the array's current state in memory:

[<li id="foo">, <li id="bar">]

It was meant just as a shorter way of saying something like this:

The result is an array with 2 DOM objects that represent the <li id="foo"> and <li id="bar"> elements, respectively.


Now, if you actually want to get the markup in the alert, you'll have to get the outer HTML of the elements. Then try:

alert($('li').map(function () { return $(this).outerHTML(); }).get());

Example: http://jsfiddle.net/cmpwM/

Community
  • 1
  • 1
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199