IE9 - document.body.appendChild issue

Written on

Whilst working on some code at work, Ellie 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);
  };
})();

Dan Palmer

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

My ears have been grooving to a lot of Coheed and Cambria, Lydia and Mike Shinoda and I am absolutely loving Toy Soldiers by Silversun Pickups.

My beaufitul face