我有一个表示页面正文的字符串,我想从中解析一些元素。我相信(随时反驳我)最好的方法是创建一个空文档,然后添加正文并使用标准 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”或(不推荐)“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 添加段落是否是最好的方法,但那是另一回事了。
关于javascript - 如何将 body 元素添加到空 DOM 文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8010932/