【问题标题】:Create a New HTML Document Including Doctype创建一个包含 Doctype 的新 HTML 文档
【发布时间】:2018-09-03 10:23:00
【问题描述】:

如果我这样做:

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

let newHTMLDocument = document.implementation.createHTMLDocument().documentElement;

newHTMLDocument.innerHTML = html;

console.log( newHTMLDocument );

输出是:

<html>
    <head>
        <title>Hello, world!</title>
    </head>
    <body>
        <p>Hello, world!</p>
    </body>
</html>

为什么不包含 doctype 标签?我需要做什么才能在输出 newHTMLDocument 时包含 doctype 标签?

【问题讨论】:

    标签: javascript html dom innerhtml outerhtml


    【解决方案1】:

    .documentElement 返回 &lt;html&gt; 元素(文档根部的元素 - - &lt;!doctype&gt; 不是元素,它是一个声明节点),所以你排除了 @ 987654326@你自己。

    如果你摆脱了.documentElementdoctype 仍然存在。

    let html = `<!doctype html>
      <html>
        <head>
            <title>Hello, world!</title>
        </head>
        <body>
            <p>Hello, world!</p>
        </body>
    </html>`;
    
    let newHTMLDocument = document.implementation.createHTMLDocument();
    newHTMLDocument.innerHTML = html;
    
    // You can access the doctype as an object:
    console.log("The <!doctype> is a node type of: " +newHTMLDocument.doctype.nodeType,
                "\nWhile the documentElement is a node type of: " + newHTMLDocument.documentElement.nodeType);
    console.log(newHTMLDocument.doctype);
    
    alert(newHTMLDocument.innerHTML);

    【讨论】:

    • 我试过你的代码,但如果我做一个 console.log(newHTMLDocument);它不包含我的元素、标题标签和 p 标签。我需要一个对象中的所有元素,因为我将在对象上使用一些 JS DOM 函数。
    • @GTSJoe newHTMLDocumemt 是一个对象,你不要直接记录它。我的代码记录它是 .innerHTML。例如,您可以使用 newHTMLDocument.querySelector() 获取其任何内容。
    • 作为参考,我最终使用了这个答案:stackoverflow.com/questions/8227612/… 它使用 createHTMLDocument doc.open(); doc.write(html); doc.close();创建一个 HTML 对象
    【解决方案2】:

    您还可以将createDocumentType()createHTMLDocument()createDocument() 一起使用:

    const doc = document.implementation.createHTMLDocument('title');
    console.log('before', new XMLSerializer().serializeToString(doc));
    
    const docType = document.implementation.createDocumentType('qualifiedNameStr', 'publicId', 'systemId');
    doc.doctype.replaceWith(docType);
    console.log('after', new XMLSerializer().serializeToString(doc));

    【讨论】:

      猜你喜欢
      • 2016-06-28
      • 2022-01-17
      • 2012-02-25
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      • 2011-08-20
      • 2021-04-04
      • 2017-02-07
      相关资源
      最近更新 更多