san
san

Reputation: 655

How to handle document.body being null on IE7 when trying to call appendChild on it

I am getting error specific to Internet Explorer 7 due to document.body being null on that platform.

The error happens when I try to do document.body.appendChild(i) in the following code:

function nm_eraseCookie(name) {
    nm_createCookie(name,"",-1)
}
var i = document.createElement('IMG');
i.src = '//e.netmng.com/pixel/?aid=403';
i.width = 1;
i.height = 1;
document.body.appendChild(i);
nm_createCookie('nm_belgacom_bt',
escape('tv1=bun_intvtel;tv2=;tv3=;phone1=hbs_discoveryline;phone2=hbs_classical_line;phone3=;inet1=bun_nettvmob;inet2=hbs_adsl_res_plus;inet3=hbs_adsl_res_go;nm_banner=;nm_popin=hbs_discoveryline;'),183);

How can I solve this issue?

Upvotes: 41

Views: 163416

Answers (6)

Utkarsh Dhiman
Utkarsh Dhiman

Reputation: 61

You can appendChild to document.body but not if the document hasn't been loaded. So you should put everything in:

window.onload=function(){
    //your code
}

This works or you can make appendChild to be dependent on something else like another event for eg.

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_doc_body_append

As a matter of fact you can try changing the innerHTML of the document.body it works...!

Upvotes: 5

Vy Le
Vy Le

Reputation: 41

If your script is inside head tag in html file, try to put it inside body tag. CreateElement while script is inside head tag will give you a null warning

<head>
  <title></title>
</head>

<body>
  <h1>Game</h1>
  <script type="text/javascript" src="script.js"></script>
</body>

Upvotes: 1

san
san

Reputation: 655

It is working. Just modify to null check:

if(document.body != null){
    document.body.appendChild(element);
}

Pointy's suggestion is good; it may work, but I didn't try.

Upvotes: 20

bob
bob

Reputation: 8005

May also want to use "documentElement":

var elem = document.createElement("div");
elem.style = "width:100px;height:100px;position:relative;background:#FF0000;";
document.documentElement.appendChild(elem);

Upvotes: 2

Konrad Gałęzowski
Konrad Gałęzowski

Reputation: 1993

In 2019 you can use querySelector for that.

It's supported by most browsers (https://caniuse.com/#search=querySelector)

document.querySelector('body').appendChild(i);

Upvotes: 2

Pointy
Pointy

Reputation: 414006

You could try

document.getElementsByTagName('body')[0].appendChild(i);

Now that won't do you any good if the code is running in the <head>, and running before the <body> has even been seen by the browser. If you don't want to mess with "onload" handlers, try moving your <script> block to the very end of the document instead of the <head>.

Upvotes: 63

Related Questions