Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot set property InnerHTML of null [duplicate]

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.

like image 322
Mj1992 Avatar asked Jun 22 '12 19:06

Mj1992


People also ask

Can innerHTML be null?

Null values do not have an innerHTML property. There are two common causes of this error: Placing a script before an element appears on the web page. Referencing the wrong element ID.

Can't assign to property innerHTML on not an object?

To solve the "Cannot set property 'innerHTML' of null" error, make sure the DOM element you're setting the innerHTML property on exists. The error most commonly occurs if you use the getElementById() method and pass it an id that is not present in the DOM. Copied! const el = document.

What is the innerHTML?

The Element property innerHTML gets or sets the HTML or XML markup contained within the element. To insert the HTML into the document rather than replace the contents of an element, use the method insertAdjacentHTML() .

What is difference between innerHTML and value?

value gives you the currently-set value of a form element (input, select, textarea), whereas . innerHTML builds an HTML string based on the DOM nodes the element contains.


1 Answers

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 <script> block just before the closing </body> tag. This could be the best solution for you, depending on your needs:

<html>
  <body>

    <!-- all of your HTML goes here... -->

    <script>
        // code in this final script element can use all of the DOM
    </script>
  </body>
</html>
  • 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.
like image 61
apsillers Avatar answered Oct 19 '22 23:10

apsillers