Why is document.body null in my javascript?

前端 未结 6 2013
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 05:50

Here is my brief HTML document.

Why is Chrome Console noting this error:

\"Uncaught TypeError: Cannot call method \'appendChild\' of nul

6条回答
  •  萌比男神i
    2020-11-28 06:40

    Your script is being executed before the body element has even loaded.

    There are a couple ways to workaround this.

    • Wrap your code in a DOM Load callback:

      Wrap your logic in an event listener for DOMContentLoaded.

      In doing so, the callback will be executed when the body element has loaded.

      document.addEventListener('DOMContentLoaded', function () {
          // ...
          // Place code here.
          // ...
      });
      

      Depending on your needs, you can alternatively attach a load event listener to the window object:

      window.addEventListener('load', function () {
          // ...
          // Place code here.
          // ...
      });
      

      For the difference between between the DOMContentLoaded and load events, see this question.

    • Move the position of your

提交回复
热议问题