Uncaught TypeError: Cannot read property 'appendChild' of null

those getting querySelector or getElementById that returns the following error:

Uncaught TypeError: Cannot read property 'appendChild' of null

or any other property, even if you have a class name or id in the HTML

don't use (defer as it is too much browser dependent.)

<script src="script.js" defer></script>  //don't use this

instead, put all your code in 'script.js' inside

$(document).ready(function(){
    //your script here.
}

Nice answers here. I encountered the same problem, but I tried <script src="script.js" defer></script> but I didn't 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.

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, therefore the element you are trying to access does not exist in the DOM yet. You will need to add defer to your script like so:

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

There isn't 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