You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将HTMLDocument对象转换为对应的HTML字符串?

How to Convert an HTMLDocument Object to a Full HTML String

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:

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:02:41