How to get innerHTML XML document (AJAX)?

After the AJAX request, an XML file is returned. I can parse this file, but when it comes to getting the "innerHTML" (or in this case "innerXML") element, a problem arises.

If the XML element, say, “content”, contains only text that I could do: content.childNodes[0].nodeValue (assuming the content refers to the XML element “content”). But this 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 contents of <content> into an existing <div> in the page, how can I do this?

Ex. myDiv.innerHTML = content.innerHTML;

+4
source share
5 answers

innerHTML is a hack that you should not use at all. Use the usual DOM functions instead:

 myDiv.appendChild(document.adoptNode(content)); 
+1
source

Try placing HTML in CDATA tags, for example:

 <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; 
+5
source

You can also use the XMLSerializer to convert the xml node 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 indicated by phihag seems more secure. However, I have not tested it either, and I'm not sure about browser compatibility.

+1
source

You can use cloneNode and appendChild :

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

If you want to use innerHTML, here's how to convert the XML markup for the first element to 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; 

While ... is used to find the first element in a content tag that skips the nodeType text type. Firefox adds nodeType text, IE6 does not work when text is not in node text.

0
source

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


All Articles