开发者

Adding XML DOM elements with jQuery- Is it possible?

I am trying to use jQuery to manipulate the DOM of an XML file I've loaded with ajax. I can select elements, empty them, and remove them, but not add them.

jQuery rarely lets me down, but I am feeling burnt out and defeated.开发者_运维问答 Please help.

The code:

<script type="text/javascript">

$.ajax({
    type: "GET",
    url: "note.xml",
    dataType: "xml",
    success: parseResultsXML
});

function parseResultsXML(xml) {

    $(xml).append('<item>something</item>'); // Nothing gets added! :(
}

</script>


I think you will need to use $.parseXML(xml) to parse the XML. parseXML() was new addition to jQuery 1.5. I had similar problem as you, and I ended up using some plugin library to parse XML because I was using jQuery 1.4.

http://api.jquery.com/jQuery.parseXML/

==== Edit ====

It's a bit tricky to manipulate XML using jQuery. Try the following code

var dom = $.parseXML(xml); //returns DOM element
var item = $.parseXML("<item>something</item>"); //returns DOM element

$(dom).children(0).append($(item).children(0))

console.log($(dom).find("item").text()); //should print "something"

You have to do $(dom).children(...) because dom is a document object, you have to wrap it into jQuery in order to use jQuery functions.

You have to do $(dom).children(0).append(...) but not $(dom).append() because dom refers to the document root of the XML DOM tree. recall all DOM looks like:

  Document
     |
    root
  /  |  \   
 c1  c2  c3 ....more children...

So if you do $(dom).append(..) you are actually trying to append to the document root which is not allowed because document root can only have one element child, namely the root element of your xml document.

Similarly, you do .append($(item).children(0)) because you want to insert the root element of item not the document root of item


The function parseResultsXML will never be called because of cross domain ajax issues, http://www.w3schools.com/xml/note.xml is in different domain than your page.

Instead copy the xml file to your site and then change the code to:

$.ajax({     
    type: "GET",     
    url: "/note.xml",     
    dataType: "xml",     
    success: parseResultsXML 
}); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜