1

如果我做:

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 标记?

4

2 回答 2

4

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

如果你摆脱了.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);

于 2018-03-25T01:48:08.643 回答
1

您还可以使用createDocumentType()withcreateHTMLDocument()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));

于 2019-11-01T22:48:37.223 回答