如何将body元素添加到空DOM文档中?

How can I add a body element to an empty DOM document?

本文关键字:DOM 文档 添加 body 元素      更新时间:2023-09-26

我有一个表示页面主体的字符串,我想对它进行一些元素解析。我相信(请随意反驳我)这样做的最好方法是创建一个空文档,然后添加主体并使用标准的JS方法来获得我想要的。
但是我似乎无法将正文添加到文档中。在chrome中,下面的代码在第2行与NO_MODIFICATION_ALLOWED_ERR: DOM Exception 7 .

 var dom = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
 dom.firstChild.innerHTML = "<body><p>Hello world</p></body>";

有什么方法可以达到我想要的吗?

由于我们比最初接受的答案早了几年,我想给出一个更现代的答案。

在Firefox 50.0.2中,你可以这样做:

document.body = document.createElement("body");
document.body.innerHTML = "<p>Hello World!</p>";

这里主体被创建并直接赋值给"document.body"。一些阅读(https://html.spec.whatwg.org/multipage/dom.html#the-body-element-2)让我明白,文档的属性"body"可以是"null"或包含类型为"body"或(不推荐)的对象。"框架"。

下面的不能工作,即产生一个空白页,因为赋值给"document"。"正文"缺失:

var body = document.createElement("body");
body.innerHTML = "<p>Hello World!</p>";

代替document.body = body;,你可以这样做:document.documentElement.appendChild(body);,而document.firstChild.appendChild(body);抛出一个错误("HierarchyRequestError: Node cannot be insertion at the specified point in hierarchy")。

有人可能会争论通过评估innerHTML来添加段落是否是最好的方法,但那是另一回事。

我注意到在最近的chrome版本中,Antoine的答案不工作-你得到一个空白页。但是,这在chrome中确实有效:

var dom = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
var body = dom.createElement("body");
dom.documentElement.appendChild(body);
// set timeout is needed because document.body is created after the current continuation finishes
setTimeout(function() {    
  document.body.innerHTML = "Hi"
},0)

不可能编辑文档根元素的innerHTML,但是可以编辑子节点。所以,这行得通:

    var dom = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
    var body = dom.createElement("body");
    body.innerHTML = "<p>hello world</p>";
    dom.firstChild.appendChild(body);

我们可以简单地写如下代码:

document.write('tagName Hello World tagName');