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.
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..?
Your
addElmfunction is wrong – you’re discarding the result ofdocument.createElement.It should be:
See 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]