javascript appendChild 错误:无法在层次结构中的指定点插入节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10744110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error with appendChild: Node cannot be inserted at the specified point in the hierarchy
提问by user1365010
There is an error with the function appendChild
: Node cannot be inserted at the specified point in the hierarchy
函数有错误appendChild
:Node cannot be inserted at the specified point in the hierarchy
JS :
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);
Can you please help me?
你能帮我么?
回答by Alnitak
You need to append to document.body
, not just document
.
您需要附加到document.body
,而不仅仅是document
.
To explain why document.appendChild
doesn't work consider the following diagram :
要解释为什么document.appendChild
不起作用,请考虑下图:
If that would be allowed that wouldn't be very useful since it will be a sibling of the HTML
root element, that make it totally outside the content.
如果允许这样做,那将不是很有用,因为它将是HTML
根元素的同级元素,这使它完全在内容之外。
For more information : Using the W3C DOM Level 1 Core