如果我这样做:
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>
元素(文档根部的元素 - - <!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);
关于javascript - 创建一个包含 Doctype 的新 HTML 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49471720/