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

时间:2011-11-04 14:38:47

标签: javascript dom

我有一个代表页面正文的字符串,我想解析一些元素。我相信(随意反驳我)最好的方法是创建一个空文档,然后添加正文并使用标准的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>";

有没有办法达到我想要的目的?

3 个答案:

答案 0 :(得分:8)

由于我们比最初接受的答案多了几年,我想提供一个更现代的答案。

在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”类型的对象或(不推荐)“frameset”。

以下工作,即生成空白页面,因为缺少对“document.body”的分配:

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

而不是document.body = body;您可以执行此操作:document.documentElement.appendChild(body);,而document.firstChild.appendChild(body);会抛出错误(“HierarchyRequestError:节点无法插入层次结构中的指定点”)。

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

答案 1 :(得分:2)

我注意到在最新版本的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)

答案 2 :(得分: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);
相关问题