简体   繁体   中英

Retrieve an HTML element inside of an XML document

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.

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"))
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM