Tuesday, October 1, 2019

javascript - Cannot set property InnerHTML of null

Answer


Answer





I've a simple html page with no code in the body tag.

I want to insert the html in the body tag through javascript.



My javascript file looks like this.



var Global={
UserWall:function(){
return "a very long html code";
}
};


var globalObject=Object.create(Global);
document.getElementsByTagName("body").item(0).innerHTML=globalObject.UserWall();


Now I want this very long html code to be auto inserted in the body tag on page load.
But it is giving me the error I've mentioned in the title.Why?



and also is this the correct way to create ajax based website(no page reloads) meaning that if I called server side script to update this very long html code and appended it to the body of the page.


Answer



You are almost certainly running your code before the DOM is constructed. Try running your code in a window.onload handler function (but see note below):




window.onload = function() {
// all of your code goes in here
// it runs after the DOM is built
}


Another popular cross-browser solution is to put your






  • Note that window.onload will wait until all images and subframes have loaded, which might be a long time after the DOM is built. You could also use document.addEventListener("DOMContentLoaded", function(){...}) to avoid this problem, but this is not supported cross-browser. The bottom-of-body trick is both cross-browser and runs as soon as the DOM is complete.


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...