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 {
  } catch (e) {
    domBody = document.documentElement.getElementsByTagName('body')[0];

  return function (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 blink-182, Lucky Chops and Danny Baranowsky and I am absolutely loving Save Us by Atreyu.

My beaufitul face