5

I want to convert a Javascript DOM HTMLDcument to a string that I can write to a file. But how do you do the string conversion of the HTMLDocument to xml?!

Update If possible I'd like to see the html that is generated once any dynamic javascript rendering has been applied.

3 Answers 3

12

The DOM way of converting HTMLDocument object to XML is:

new XMLSerializer().serializeToString(oDocument);

In Internet Explorer there is no way to get proper XML representation of HTML document object by any built-in means. There you would need to implement serialization mechanism yourself - traversing the DOM tree and creating XML string.

Sign up to request clarification or add additional context in comments.

2 Comments

Would it display the rendered HTML? i.e. that which is rendered once the browser has loaded the document and applied any dynamic Javascript?
Joel, It is farely simple to test. To my understanding it should display the rendered HTML since the parameter of the serializeToStringfunction is the live DOM Node (document).
5
'<html>'+document.documentElement.innerHTML+'</html>'

1 Comment

This is the short term solution I used, I'm hoping for a more comprehensive solution that writes out the html that is generated once the document has loaded and any dynamic javascript rendering has been applied. Sergey's solution below looks promising.
0

You could create a new div node, append the HTMLDocument as a child, and then read the innerHTML of the parent div, as shown below,

var div = document.createElement("div");
div.appendChild(oDocument);

console.log(div.innerHTML);

1 Comment

This throws Uncaught DOMException: Node.appendChild: May not add a Document as a child

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.