Why when using jQuery replaceWith () does the <constructor> tag lead to 'undefined'?
I am using jQuery to edit XML. Yes, I know that is probably a bad idea.
I came across some very strange behavior (bug?) When using the xml <constructor> . Replacing existing XML with this tag causes the tag to be 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 am trying to execute. So far, only <constructor> has this problem.
Any idea what is going on? Is this because jQuery is designed to handle HTML, not XML? Any workarounds I can use?
+5
1 answer
Your problem appears as replacing an xml object with an 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> +2