gpt4 book ai didi

javascript - 创建一个包含 Doctype 的新 HTML 文档

转载 作者:行者123 更新时间:2023-11-28 17:34:23 24 4
gpt4 key购买 nike

如果我这样做:

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你自己。

如果你去掉.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);

关于javascript - 创建一个包含 Doctype 的新 HTML 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49471720/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com