Home » Jquery » javascript – Load multiple XML and append each to a temp XML object?

javascript – Load multiple XML and append each to a temp XML object?

Posted by: admin February 22, 2020 Leave a comment

Questions:

I want to declare and create a temporary XML object like:

var temp_xml = '<time></time>';
var parsed = $.parseXML( temp_xml );
temp_xml = $( parsed );

Then, I’d like to take a loaded XML file and add it to temp_xml. Examples of what I’ve tried (not all at the same time, I’m just saving space here):

function xmlLoaded(data) {
    temp_xml.append(data); // Attempt 1 - TypeError: document is null
    $(temp_xml).append(data); // Attempt 2 - TypeError: document is null
    $(temp_xml).appendChild(data); // Attempt 3 - $(...).appendChild is not a function
    $(temp_xml).find('time').each(function() {
        $(data).appendTo($(this))
    }); // Attempt 4 - context is null
}

In case you need to know, the following is what loads the XML files:

$.ajax({
    type: "GET",
    url: urlVar,
    dataType: "xml",
    success: xmlLoaded
});

End result would be: <time><year id="2020">...</year><year id="2021">...</year><year id="2022">...</year></time>

I’ve searched, I’ve read, I’ve cried. I can’t find an exact example of this and, as you can see, my attempts to modify similar examples always result in error.

How to&Answer:

I knew I was just having a “senior moment”.
Attempt 4 was correct, BUT I was forgetting the super-important .find(‘year’) for $(data).

function xmlLoaded(data) {
    $(temp_xml).find('time').each(function() {
        $(data).find('year').appendTo($(this))
    });

}