5

I'm creating an HTML document object:

let newHTMLDocument = document.implementation.createHTMLDocument();

let html = `<!DOCTYPE html>
<html>
    <head>
        <title>Hello, world!</title>
    </head>
    <body>
        <p>Hello, world!</p>
    </body>
</html>`;

newHTMLDocument.open();
newHTMLDocument.write( html );
newHTMLDocument.close();

console.log( String(newHTMLDocument) ); // [object HTMLDocument]

Instead of "[object HTMLDocument]," how can I convert newHTMLDocument into a string containing all of the HTML code, including the doctype and html tag?

3 Answers 3

8

try this one console.log(new XMLSerializer().serializeToString(newHTMLDocument)) it will grab html content from document into string format

demo

jsbin

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

5 Comments

This doesn't work. It doesn't return the doctype, which I need in order to be a full representation of the original HTML document code.
@GTSJoe try this console.log( newHTMLDocument.documentElement.outerHTML );
@uzauf I need the <doctype> too.
try this one console.log(new XMLSerializer().serializeToString(newHTMLDocument))
Yes, that's it! Thank you, Uzaif! Please update your answer to include console.log(new XMLSerializer().serializeToString(newHTMLDocument)).
1

You can use console.log(newHTMLDocument.documentElement);

Comments

0

You can use innerhtml property of the element.do this thing.

ele = newHTMLDocument.getElementByTagName('html') console.log(ele[0].innerHTML);

Comments

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.