开发者

How to get the innerHTML of a XML document (AJAX)?

After an AJAX query, a XML file is returned. I'm able to "parse" that file, but when it comes to getting the "innerHTML" (or in this case "innerXML") of an element, the issue arises.

If the XML element, let's say "content", only contained text I could do: content.childNodes[0].nodeValue (assuming that content references the XML element "content"). But that element contains开发者_开发百科 other elements:

<stackoverflow reason="tribute to this page">
   <content>
      <div><span><p>Some more HTML elements</p></span></div>
   </content>
</stackoverflow>

I need to copy the content of <content> to an existing <div> in the page, how could I do that?

Ex. myDiv.innerHTML = content.innerHTML;


Try placing the HTML within CDATA tags, like so:

<stackoverflow reason="tribute to this page">
   <content>
      <![CDATA[<div><span><p>Some more HTML elements</p></span></div>]]>
   </content>
</stackoverflow>

Then just insert the data into your element via innerHTML.

document.getElementById('target').innerHTML = content.childNodes[0].nodeValue;


You can also use XMLSerializer to convert the xml node back to a string representation and then use innerHTML to copy it to the element:

div.innerHTML = 
  (new XMLSerializer()).serializeToString(content.childNodes[0].nodeValue)

However the solution pointed out by phihag looks to be the safer one. However, I did not test either, and I'm not sure about browser compatibility.


innerHTML is a hack you should not use at all. Instead, use the normal DOM functions:

myDiv.appendChild(document.adoptNode(content));


You could use cloneNode and appendChild:

myDiv.appendChild(content.childNodes[0].cloneNode(true));


If you want to use innerHTML, here is how to convert the XML markup for the first Element into a string

//Where oXML is the xml document or xml object
var XMLString;
oXML=oXML.getElementsByTagName('content')[0].firstChild;
//nodeType 1-Element,2-Attr,3-Text.....
while(oXML.nodeType!=1){oXML=oXML.nextSibling;}
//code for IE and Mozilla, Firefox, Opera, etc. respectively
XMLString=(oXML.xml)?oXML.xml:(new XMLSerializer()).serializeToString(oXML);
myDiv.innerHTML=XMLString;

The while... is used to find the first element within the content tag, skipping text nodeType. Firefox adds the text nodeType, IE6 does not when no text is within the text node.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜