javascript 未捕获的错误:NOT_FOUND_ERR:appendChild 调用的 DOM 异常 8
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11640367/
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
Uncaught Error: NOT_FOUND_ERR: DOM Exception 8 for appendChild call
提问by user5243421
Possible Duplicate:
javascript appendChild doesn't work
The error occurs on the last line of this snippet:
错误发生在此代码段的最后一行:
var anchor = "<a id=\"hostname\" href=\"" + destination + "\"> "+ imagename + "</a>";
var specialdiv = document.getElementById("specialdiv");
console.log("div: " + specialdiv);
specialdiv.appendChild(anchor);
There's really nothing else going on... I verified that specialdiv
isn't null or something like that. Can anyone explain why I'm getting this error on that line?
真的没有其他事情发生......我确认它specialdiv
不是空的或类似的东西。谁能解释为什么我在那条线上收到这个错误?
回答by Kristian
don't pass a string, but an element
不要传递字符串,而是传递元素
var link = document.createElement('a');
link.innerHTML = imagename;
link.id = "hostname";
link.href = destination;
var specialdiv = document.getElementById("specialdiv");
specialdiv.appendChild(link);
回答by Rocket Hazmat
You are getting that error because appendChild
takes DOM elements, not strings. You need to actually create a DOM element before using appendChild
.
您收到该错误是因为appendChild
需要 DOM 元素,而不是字符串。在使用之前,您需要实际创建一个 DOM 元素appendChild
。
var anchor = document.createElement('a');
anchor.id = "hostname";
anchor.href = destination;
anchor.innerHTML = imagename;
var specialdiv = document.getElementById("specialdiv");
specialdiv.appendChild(anchor);