Javascript 如何将body元素添加到空DOM文档中?
我有一个表示页面主体的字符串,我想对其进行一些元素分析。我相信(尽管反驳我)最好的方法是创建一个空文档,然后添加正文并使用标准的JS方法来获得我想要的内容。Javascript 如何将body元素添加到空DOM文档中?,javascript,dom,Javascript,Dom,我有一个表示页面主体的字符串,我想对其进行一些元素分析。我相信(尽管反驳我)最好的方法是创建一个空文档,然后添加正文并使用标准的JS方法来获得我想要的内容。 但我似乎无法将正文添加到文档中。在chrome中,以下代码在第2行失败,不允许修改错误:DOM异常7 var dom = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null); dom.firstChild.innerHT
但我似乎无法将正文添加到文档中。在chrome中,以下代码在第2行失败,不允许修改错误:DOM异常7
var dom = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
dom.firstChild.innerHTML = "<body><p>Hello world</p></body>";
var dom=document.implementation.createDocument('http://www.w3.org/1999/xhtml','html',空);
dom.firstChild.innerHTML=“Hello world”;
有什么方法可以实现我想要的吗?不可能编辑文档根元素的innerHTML,但是可以编辑子节点的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);
var dom=document.implementation.createDocument('http://www.w3.org/1999/xhtml','html',空);
var body=dom.createElement(“body”);
body.innerHTML=“hello world”;
dom.firstChild.appendChild(body);
我注意到,在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)
由于我们比最初接受的答案要晚一些年,我想给出一个更现代的答案 在Firefox 50.0.2中,您可以执行以下操作:
document.body = document.createElement("body");
document.body.innerHTML = "<p>Hello World!</p>";
document.body=document.createElement(“body”);
document.body.innerHTML=“你好,世界!”;
在这里,主体被创建并直接分配给“document.body”。
一些阅读()让我明白,文档的属性“body”可以是“null”,也可以包含类型为“body”或(不推荐)“frameset”的对象
由于缺少“document.body”的赋值,以下操作不起作用,即生成一个空白页:
var body = document.createElement("body");
body.innerHTML = "<p>Hello World!</p>";
var body=document.createElement(“body”);
body.innerHTML=“你好,世界!”;
而不是document.body=body代码>您可以这样做:document.documentElement.appendChild(body)
,而document.firstChild.appendChild(body)代码>引发错误(“HierarchyRequestError:无法在层次结构中的指定点插入节点”)
有人可能会争论通过评估innerHTML添加段落是否是最好的方法,但那是另一回事。可能重复:这在chrome 40.0.2214.93 m中不起作用。如果我把它放在一个脚本标记中,我会得到一个空白页。我注意到,添加到body对象上的任何内容都不会出现,但如果设置timeout(function(){document.body.innerHTML=“something”},0),它会出现work@Mahi我不知道。为什么不试试,然后在这里报告呢?:)我认为document是object,body是node,所以我们不能这样做?如果页面上没有body,那么就不会有document.body。这就是这个问题的重点。我想我不明白你的困惑下午好。我认为我们也不能做html.createElement
为什么文档只能创建元素为什么其他元素不能创建元素?