我写了以下代码
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);
我的文档中有id为“myExistingElmId”的元素。 这条线
root.appendChild(elm);
在控制台中给出了以下错误
Uncaught error: NOT_FOUND_ERR: DOM Exception 8
为什么会这样?..
答案 0 :(得分:3)
document
不是DOM元素,document.body
是。正如@Alnitak所说,你失去了document.createElement
的结果。这段代码应该可以工作:
function addElm(root,elm) {
var elm = document.createElement(elm);
if(!root) {
root = document.body;
}
root.appendChild(elm);
return elm;
}
答案 1 :(得分:2)
您的addElm
功能有误 - 您放弃了document.createElement
的结果。
应该是:
function addElm(root, type) {
var elm = document.createElement(type);
if(!root) {
root = document.body;
}
root.appendChild(elm);
return elm;
}
请参阅http://jsfiddle.net/alnitak/wAuvJ/
[@ Ethan也是正确的,它应该是document.body
,但这是因为你没有行使代码路径而看到的实际错误的附带情况]