Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the tag <constructor> result in 'undefined' when using jQuery replaceWith()?

I'm using jQuery to edit XML. Yes, I know that's probably a bad idea.

I came across some very strange behavior (a bug?) when using the xml tag <constructor>. Replacing existing XML with this tag results in the tag being surrounded by 'undefined'.

$(document).ready(function(){
    var my_xml = $.parseXML("<document><old>original xml</old></document>");
    var new_xml_string = '<constructor>Foobar</constructor>';
    var old_node = $(my_xml).find('old');
    old_node.replaceWith(new_xml_string);
    var my_xml_string = (new XMLSerializer()).serializeToString(my_xml);
    console.log(my_xml_string);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

This code works fine for any other tag I try. So far only <constructor> seems to have this problem.

Any idea what's going on? Is this because jQuery is meant for processing HTML, not XML? Any workarounds I can use?

like image 633
Agargara Avatar asked Oct 29 '22 01:10

Agargara


1 Answers

Your issue appears as replacing xml object with xml string. You should replace xml object with xml object.

$(document).ready(function(){
    var my_xml = $.parseXML("<document><old>original xml</old></document>");
    var new_xml= $.parseXML("<document><constructor>Foo</constructor></document>");
    var new_xml_const = $(new_xml).find('constructor');
    var old_node = $(my_xml).find('old');
    old_node.replaceWith(new_xml_const);
    var my_xml_string = (new XMLSerializer()).serializeToString(my_xml);
    console.log(my_xml_string);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
like image 117
artgb Avatar answered Nov 15 '22 04:11

artgb