[英]Javascript HTMLDOM appendChild results in DOM exception 8
I have written the following code 我写了下面的代码
function byId(id) {
return document.getElementById(id);
}
function addElm(root,elm) {
document.createElement(elm);
if(!root) {
root = document;
}
root.appendChild(elm);
return elm;
}
document.addEventListener('DOMContentLoaded',function() {
var elm = byId('myExistingElmId');
addElm(elm,'span');
},false);
The element having id "myExistingElmId" is there in my document. 我的文档中有ID为“ myExistingElmId”的元素。 The line 线
root.appendChild(elm);
is giving me the following error in console 在控制台中给我以下错误
Uncaught error: NOT_FOUND_ERR: DOM Exception 8
Why is this happening..? 为什么会这样呢?
document
is not a DOM element, document.body
is. document
不是DOM元素, document.body
是。 And as @Alnitak said, you lost the result of document.createElement
. 正如@Alnitak所说,您丢失了document.createElement
的结果。 This code should be work: 这段代码应该可以工作:
function addElm(root,elm) {
var elm = document.createElement(elm);
if(!root) {
root = document.body;
}
root.appendChild(elm);
return elm;
}
Your addElm
function is wrong - you're discarding the result of document.createElement
. 您的addElm
函数是错误的-您正在舍弃document.createElement
的结果。
It should be: 它应该是:
function addElm(root, type) {
var elm = document.createElement(type);
if(!root) {
root = document.body;
}
root.appendChild(elm);
return elm;
}
See http://jsfiddle.net/alnitak/wAuvJ/ 参见http://jsfiddle.net/alnitak/wAuvJ/
[@Ethan is also correct that it should be document.body
, but that's incidental to the actual error you were seeing as you weren't exercising that code path] [@Ethan也应该是document.body
也是正确的,但这与您在不执行该代码路径时看到的实际错误是偶然的]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.