gpt4 book ai didi

javascript - DOM 节点生成 HTML5 可能吗?

转载 作者:行者123 更新时间:2023-12-02 23:53:50 25 4
gpt4 key购买 nike

我想使用 DOM 节点方法生成 html5 文件,可以吗?

我已经尝试过制作,但是我找不到正确的代码来生成“!DOCTYPE”模板。

我想要这样的结构:

<!DOCTYPE html>
........
.......
.....
...
..
</html>

最佳答案

当然,您可以生成 节点,您只需使用 document.implementation.createDocumentType()方法。

但是,生成 HTML5 文档是相当大的负担(至少在字符串化方面)。事实上,没有 HTML5 命名空间,一旦在 DOM 中解析,您的 HTML5 文档实际上就是 XHTML:

console.log(document.documentElement.namespaceURI);

因此,当您对该文档进行字符串化时,您的所有元素都将具有 xmlns="http://www.w3.org/1999/xhtml" 属性。

为了避免这种情况,您实际上需要使用 null 命名空间生成所有元素:

// Our <!DOCTYPE html> node
const doctype = document.implementation.createDocumentType('html', '', '');
// A new HTML5 document
const doc = document.implementation.createDocument("", 'html', doctype);

// We need to force null NS
const body = doc.createElementNS(null, 'body');
body.appendChild(doc.createTextNode('hello'));

doc.documentElement.appendChild(body);

const str = (new XMLSerializer).serializeToString(doc);

console.log(str);

关于javascript - DOM 节点生成 HTML5 可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55509917/

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