Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot insert elements in a jQuery XML object

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.

like image 932
jake Avatar asked Nov 10 '11 17:11

jake


1 Answers

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/

like image 150
JaredPar Avatar answered Sep 30 '22 06:09

JaredPar