Reputation: 6124
I have an XML document with a structure like this:
<pod id="1">
Lorem ipsum....
<subpod>
<img src="example.gif">
</subpod>
</pod>
<pod id="2">
Lorem ipsum....
<subpod>
<img src="example2.gif">
</subpod>
</pod>
I have retrieved the XML file through a jQuery $.get()
request, and now I want to embed the images into my document. This is the code I have tried:
$.get(queryURL, function (data) {
var pods = $(data).find("pod");
if (pods.length !== 0) {
$("#container").html('<div id="podcontainer">' + $(pods[0]).find("img")[0] + $(pods[1]).find("img")[0] + '</div>');
}
});
However, all I get when I run this is
[object Element][object Element]
I have also tried turning them into jQuery objects like so: $($(pods[0]).find("img")[0])
, which returns
[object Object][object Object]
Using the jQuery $.parseHTML()
function gives
null null
I don't understand why it is doing this, because when I log the elements in the console they show up as valid HTML elements.
Upvotes: 0
Views: 230
Reputation: 1074335
The problem is that you're doing string concatenation:
$("#container").html('<div id="podcontainer">' + $(pods[0]).find("img")[0] + $(pods[1]).find("img")[0] + '</div>');
...but the elements aren't strings, they're elements. When you convert an element to a string, you get..."[object Element]"
.
The solution is: Don't do string concatenation. Here's one way:
var div = $('<div id="podcontainer"></div>');
div.append($(pods[0]).find("img"));
div.append($(pods[1]).find("img"));
$("#container").html(div);
Technically, you can do this without the variable:
$("#container").html(
$('<div id="podcontainer"></div>')
.append($(pods[0]).find("img"))
.append($(pods[1]).find("img"))
);
Upvotes: 1