Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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?

Good pointing out running the script in the <head>. I kept getting a Cannot call method 'appendChild' of null because of this. Moving it to the end of the document fixed it as the '<body>' did not exist when it was running in the head. – pbojinov Jan 22, 2013 at 8:33

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

In 2019 you can use querySelector for that.

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

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

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

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

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.