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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:53:15  来源:igfitidea点击:

Error with appendChild: Node cannot be inserted at the specified point in the hierarchy

javascriptappendchild

提问by user1365010

There is an error with the function appendChild: Node cannot be inserted at the specified point in the hierarchy

函数有错误appendChildNode 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);

http://jsfiddle.net/T7ZMX/

http://jsfiddle.net/T7ZMX/

Can you please help me?

你能帮我么?

回答by Alnitak

You need to append to document.body, not just document.

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

To explain why document.appendChilddoesn't work consider the following diagram :

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

DOM Tree

DOM树

If that would be allowed that wouldn't be very useful since it will be a sibling of the HTMLroot element, that make it totally outside the content.

如果允许这样做,那将不是很有用,因为它将是HTML根元素的同级元素,这使它完全在内容之外。

For more information : Using the W3C DOM Level 1 Core

更多信息:使用 W3C DOM Level 1 Core