I'm using the new $.parseXML() method with jQuery 1.5 to parse a string into a valid XML object. Once I convert the string to a jQuery XML object, I am able to navigate the DOM of the XML and look up values. I can even change the values of different attributes. However, I cannot insert new elements into the XML, even though I believe this is supposed to be possible. Below is a code snippet that illustrates the issue:
var myXml = "<one attr='a'><two attr='b'/><three attr='c'><four attr='d'/></three></one>";
myXml = $.parseXML(myXml);
$(myXml).find('two').attr('attr','new value'); //<-- This works
alert($(myXml).find('two').attr('attr')); //<-- This works too
$(myXml).find('three').append('<five>some value</five>'); //<-- Does not work
alert($(myXml).find('five').text()) // <--Null
Does anyone have ideas on making this work? Thanks in advance.
The problem here is that you're appending a string instead of a DOM element. To append a DOM element you need to wrap the new XML in a $(...)
expression
$(myXml).find('three').append($('<five>some value</five>'));
Fiddle: http://jsfiddle.net/kDmD8/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With