将 [object HTMLDocument] 转换为字符串

GTS*_*Joe 5 html javascript dom

我正在创建一个 HTML 文档对象:

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]
Run Code Online (Sandbox Code Playgroud)

如何将 newHTMLDocument 转换为包含所有 HTML 代码(包括 doctype 和 html 标记)的字符串,而不是“[object HTMLDocument]”?

uza*_*aif 8

试试这个,console.log(new XMLSerializer().serializeToString(newHTMLDocument)) 它会将文档中的 html 内容抓取为字符串格式

演示

jsbin