创建包含Doctype的新HTML文档

时间:2018-03-25 01:40:05

标签: javascript html dom innerhtml outerhtml

如果我这样做:

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

2 个答案:

答案 0 :(得分:3)

.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);

答案 1 :(得分:0)

您也可以将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));