[JavaScript] About Uncaught TypeError: Cannot set properties of null (setting 'innerHTML') error

question:

Uncaught TypeError: Cannot set properties of null (setting 'innerHTML') means Uncaught TypeError: Cannot set properties of null (setting 'innerHTML').

error code:

Output content: When executing getElementById.innerHTML, the content of the demo cannot be found, and the place where you want to insert the written HTML code cannot be found. As shown in the picture:

 

Analyze the reasons:

This problem involves the loading and execution of Javascript scripts in HTML, browsers always load the entire HTML DOM from top to bottom. Any js code written in the tag will be executed by the browser rendering engine, even before loading the various HTML element tags in the entire body tag. When the innerHTML line of code is executed, the following DOM structure is not loaded, so an error will be reported and the HTML cannot be read.

DOM document loading steps: 

  1. Parse the HTML structure 
  2. Load external scripts and stylesheets 
  3. Parse and execute script code 
  4. Execute $(function(){})the corresponding code in 
  5. Load binary resources such as images 
  6. After the page is loaded, executewindow.onload

Solution:

Method 1: Put the js at the bottom, wait for the browser to fully load the DOM from top to bottom, and then execute the js script, and there will be no null references.

Code example:

 Output result:

 Method 2: Use the event hook window.onload , add window.onload to the original script tag , let the browser execute the script after loading the DOM.

Code example:

 Output result:

 Reference link: Loading and execution of Javascript scripts in HTML_Cassie's blog-CSDN博客_htmlExecute js code

javascript - Cannot set property 'innerHTML' of null - Stack Overflow

Guess you like

Origin blog.csdn.net/aDiaoYa_/article/details/122506390