Why is document.body null? Javascript | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why is document.body null? Javascript

I created the following code: function btn(text, does) { var button = document.createElement("button"); button.innerHTML = text; button.addEventListener("click" , does ); document.body.appendChild(button); }//ends function btn function say() { document.write("text"); } btn("Click me", say ); This code results in a error: "Cannot read property 'appendChild' of null" From my googling I learned that the issues is that document.body is null (appendChild is a property of document.body but d.b is null so it cannot read it). Why is my document.body null? I think other people have been able to run this code just fine, yet it does not work for me. I have tried it on IE, Edge and Chrome. Thanks Link to this code: https://code.sololearn.com/W7QAzI0bkJs3/#js (I hope it works)

4th Dec 2019, 10:07 PM
JJ McSquiggles
JJ McSquiggles - avatar
2 Answers
+ 5
I believe your function is being called before the body is created. To solve this, wrap the function inside an onload event to ensure everything has been loaded in window.onload = function(){ btn("click me", say) }
5th Dec 2019, 12:13 AM
Jax
Jax - avatar
+ 1
THANK YOU! It works now
5th Dec 2019, 5:25 PM
JJ McSquiggles
JJ McSquiggles - avatar