Search code examples
javascriptexceptionappendchilddom

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. 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..?


Solution

  • Your addElm function is wrong - you're discarding the result of 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/

    [@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]