Cannot insert elements into jQuery XML object

I am using the new $ .parseXML () method with jQuery 1.5 to parse a string in a valid XML object. Once I convert the string to a jQuery XML object, I can navigate the XML DOM and look for values. I can even change the values โ€‹โ€‹of different attributes. However, I cannot insert new elements into XML, although I believe that this is possible. Below is a code snippet that illustrates the problem:

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 any ideas on this job? Thanks in advance.

+6
source share
1 answer

The problem is that you are adding a line instead of a DOM element. To add a DOM element, you need to wrap the new XML in the expression $(...)

 $(myXml).find('three').append($('<five>some value</five>')); 

Fiddle: http://jsfiddle.net/kDmD8/

+8
source

Source: https://habr.com/ru/post/901228/


All Articles