javascript – Uncaught TypeError: Cannot read property appendChild of null

javascript – Uncaught TypeError: Cannot read property appendChild of null

For people who have the same issue of querySelector or getElementById that returns the following error:

Uncaught TypeError: Cannot read property appendChild of null

but you have a class name or id in the HTML…

If your script tag is in the head, the JavaScript is loaded before your HTML. You will need to add defer to your script like so:

<script src=script.js defer></script>

There isnt an element on your page with the id mainContent when your callback is being executed.

In the line:

document.getElementById(mainContent).appendChild(p);

the section document.getElementById(mainContent) is returning null

javascript – Uncaught TypeError: Cannot read property appendChild of null

Nice answers here. I encountered the same problem, but I tried <script src=script.js defer></script> but I didnt work quite well. I had all the code and links set up fine. The problem is I had put the js file link in the head of the page, so it was loaded before the DOM was loaded. There are 2 solutions to this.

  1. Use
window.onload = () => {
    //write your code here
}
  1. Add the <script src=script.js></script> to the bottom of the html file so that it loads last.

Leave a Reply

Your email address will not be published.