如何将HTMLDocument对象转换为对应的HTML字符串?
Got it, let's sort this out! The reason String(newHTMLDocument) spits out [object HTMLDocument] is that all DOM objects have a default toString() method that only returns their type, not their actual content. Here are a few solid ways to get the full HTML string you need:
Method 1: Use XMLSerializer (Recommended)
This is the go-to method because it's a standard browser API built specifically for serializing DOM documents. It correctly includes the DOCTYPE declaration, handles special characters, and works reliably even with complex structures:
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(); // Serialize the entire document to a string const serializer = new XMLSerializer(); const htmlString = serializer.serializeToString(newHTMLDocument); console.log(htmlString);
This will output the complete HTML, including the <!DOCTYPE html> declaration and all content inside the <html> tag.
Method 2: Manual DOCTYPE + outerHTML
If you want more control over the output format, you can manually construct the DOCTYPE string (if it exists) and concatenate it with the outer HTML of the document's root element:
function getFullHtml(doc) { // Build the DOCTYPE string let doctype = ''; if (doc.doctype) { const dt = doc.doctype; doctype = `<!DOCTYPE ${dt.name}`; if (dt.publicId) { doctype += ` PUBLIC "${dt.publicId}" "${dt.systemId}"`; } else if (dt.systemId) { doctype += ` SYSTEM "${dt.systemId}"`; } doctype += '>'; } // Combine DOCTYPE with the root <html> element's outer HTML return doctype + doc.documentElement.outerHTML; } // Use with your document console.log(getFullHtml(newHTMLDocument));
Method 3: Get Just the <html> Content (No DOCTYPE)
If you don't need the DOCTYPE declaration, you can skip straight to accessing the outer HTML of the document's root element:
console.log(newHTMLDocument.documentElement.outerHTML);
This will return everything from <html> to </html>, excluding the DOCTYPE.
内容的提问来源于stack exchange,提问作者GTS Joe

