6

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.

1 Answer 1

8

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/

Sign up to request clarification or add additional context in comments.

2 Comments

I feel so foolish for overlooking that. Thanks for the quick answer!
@jake don't feel foolish. Everyone makes mistakes. That's what stackoverflow is for ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.