如果我这样做:
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标签?
.documentElement
返回 <html>
element(文档根的元素 - <!doctype>
不是一个元素,它是声明节点(,因此您排除了doctype
自己。
如果您摆脱了.documentElement
,则doctype
剩下。
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);
您也可以将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));