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

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

最佳答案

<强> .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/

相关文章:

javascript - 按属性更改光标

javascript - 如何使用 react-select 和 react-bootstrap 来获取值

javascript - 使用包括脚本的长 block 动态更改 div 的源/内容

html - 通用表示 block 与通用结构 block

javascript - 将 HTML 元素位置更改为另一个位置 javascript

jquery - 如何将目标 ="_blank"放入 jQuery 中?

javascript - 如何通过点击的类获取元素的索引

javascript - Bootstrap 轮播中的四个项目 Ng 重复?

html - 当我想将 css 样式应用于文本 block 时,使用什么标签最理想?

PHP domdocument 插入 Â 符号