appendChild出错:无法在层次结构中的指定点插入节点

时间:2012-05-24 19:32:11

标签: javascript appendchild

函数appendChild出错:无法在层次结构中的指定点插入节点

JS:

var abc=document.createElement("div");
abc.style.position="absolute";
abc.style.width="10px";
abc.style.height="10px";
abc.style.left="10px";
abc.style.top="10px";
abc.style.backgroundColor="black";
abc.innerHTML="abc";
document.appendChild(abc);

http://jsfiddle.net/T7ZMX/

你能帮帮我吗?

1 个答案:

答案 0 :(得分:28)

您需要附加到document.body,而不仅仅是document

要解释为什么document.appendChild不起作用,请考虑以下图表:

DOM Tree

如果允许这样做不会非常有用,因为它将是HTML根元素的兄弟,这使得它完全在内容之外。

有关详细信息:Using the W3C DOM Level 1 Core