Search code examples
javascriptdomdomparser

JavaScript/DOM: Unable to append XML from DOMParser


I'm trying to take XML and append it to an element however regardless of how I do this (appendChild, insertBefore, replaceChild etc) I keep receiving errors in all browsers including the latest versions.

Here is the relevant code...

var s = '<div xmlns="http://www.w3.org/1999/xhtml">'+document.getElementById('xml_textarea').value+'</div>';

var xml = new DOMParser().parseFromString(s,'application/xml');

document.getElementById('example').appendChild(xml);

The following is text that is being interpreted by the DOMParser (SO keeps incorrectly interpreting paragraphs so obviously the spaces inside each element are only to get around the site's parse error)...

< p >111< /p >

< p >222< /p >

< p >333< /p >

What exactly am I missing that is preventing the object from being added to the page?

  • I would like to keep using the application/xml media type/mime though have tested text/xml without success.
  • No frameworks, period.

Solution

  • Apparently the owner document was different so I have to use importNode...

    document.getElementById('example').appendChild(document.importNode(xml.getElementsByTagName('div')[0],true));