admin管理员组

文章数量:1410674

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.

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.

Share Improve this question asked Nov 10, 2011 at 17:15 jakejake 1,9393 gold badges23 silver badges31 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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/kDmD8/

本文标签: javascriptCannot insert elements in a jQuery XML objectStack Overflow