My beaufitul face

Dan Palmer

Hello. I work for Condé Nast Britain as a front end developer. I usually tweet a lot of crap whilst listening to a lot of music. My nickname is Gonads. I wear shorts all year round.

IE9 - document.body.appendChild issue

written on Jan 8, 2013

Whilst working on some code at work, jack and I bumped into a problem with IE9. It wouldn’t allow us to append any divs directly to the body. We tried appendChild and insertBefore but both failed us.

We read up and initially thought the issue could have been due to a few divx plugins but again, this was not the case.

After chatting with Pedro, he suggested that we try using document.documentElement instead of the body. The crying then changed from sadness, to happiness.

I whipped up a little snippet that I will probably need again and felt like sharing as I couldn’t find a good fix.

var fnAppendToBody = (function() {

  var domBody = document.body;

  try {
    domBody.appendChild(document.createElement('div'))
  } catch (e) {
    domBody = document.documentElement.getElementsByTagName('body')[0];
  }

  return function(domElm) {
    domBody.appendChild(domElm);
  }
})();