1

Okay, hopefully I didn't miss a thread that is making this a duplicate. Everything I found was about AJAX requests with jQuery, whereas I'm not working with AJAX, and I'm using native JS.

Basically, I'm creating a DOM parser, and then an XML document from that.

var parser = new DOMParser();
var doc = parser.parseFromString(HTML, "text/xml");

Once I do my manipulation, I need to XML as a string, not an object.

In Chrome, I can just do doc.innerHTML, but IE doesn't even have an innerHTML attribute, which makes sense since it is XML and not HTML.

I know I can create a new node, and copy all children over to that, then get the innerHTML, but is there a better / faster way than that to just get the string representation of an XML document?

Thanks.

David
  • 4,744
  • 5
  • 33
  • 64
  • Presumably *HTML* is the string you are parsing, is it HTML or XML? You can also use [*XMLSerializer*](https://developer.mozilla.org/en-US/docs/Web/Guide/Parsing_and_serializing_XML#Part_2.3A_how_to_serialize_the_content_of_a_given_XML_document) for serialising the DOM. IE (i.e. Microsoft) invented *innerHTML*, it's been standardised by the W3C, MS might not have kept up. – RobG Jan 07 '15 at 00:58
  • `.innerHTML` doesn't make much sense for non-HTML _XML_ – Paul S. Jan 07 '15 at 01:14
  • @RobG, You are corrent, HTML is the string to be parsed, and it is HTML. The reason I'm using `text/xml` is because IE doesn't support `text/html` far enough back. But everything is valid HTML – David Jan 07 '15 at 01:15
  • I tried your code in Safari, Firefox and Chrome 39 and for all, `doc.innerHTML` returns *undefined*. *DOMParser* is not supported in IE 6 (dunno if you're going back that far). Copying nodes across to a div doesn't seem hard, as long as they are all valid child nodes of a div (e.g. no head or style elements). Does this question help: [*In JavaScript, how can serializer part of the DOM to XHTML?*](http://stackoverflow.com/questions/7576925/in-javascript-how-can-serializer-part-of-the-dom-to-xhtml) – RobG Jan 07 '15 at 01:49
  • Nah, IE9 is my support on this project. I ended up using your first link. As simple as: `var xml = new XMLSerializer();` and `xml.serializeToString(doc)`. Gets me exactly what I needed – David Jan 07 '15 at 01:54
  • 1
    It seems *XMLSerializer* is [*available in IE 9+*](http://blogs.msdn.com/b/ie/archive/2010/10/15/domparser-and-xmlserializer-in-ie9-beta.aspx), so maybe you only need the div hack for IE 8? Feature test for support and fallback if required. – RobG Jan 07 '15 at 01:54

0 Answers0