Solve - Cannot read property 'appendChild' of Null in JS

avatar

Borislav Hadzhiev

Sat Oct 23 20212 min read

Solve - Cannot read property 'appendChild' of Null #

The "Cannot read property 'appendChild' of null" error occurs for 2 reasons:

  1. Calling the appendChild() method on a DOM element that doesn't exist, e.g calling getElementById with invalid id.
  2. Inserting the JS script tag above the HTML, where the DOM elements are declared.
index.js
const el = null; const p = document.createElement('p'); // โ›”๏ธ Cannot read properties of null (reading 'appendChild') el.appendChild(p);

To solve the "Cannot read property 'appendChild' of null" error, make sure the DOM element on which you're calling the method exists. The error often occurs after providing an invalid id to the getElementById method.

index.js
const el = document.getElementById('does-not-exist'); console.log(el); // ๐Ÿ‘‰๏ธ null const p = document.createElement('p'); // โ›”๏ธ Cannot read properties of null (reading 'appendChild') el.appendChild(p);

Because we provided an id that doesn't exist in the DOM, we got back a null value, on which we tried to call the appendChild method and got the error.

To solve the "Cannot read property 'appendChild' of null" error, make sure to insert the JS script tag at the bottom of the body. The JS script tag should be placed after the HTML elements have been declared.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- โ›”๏ธ BAD - script is ran before HTML is declared โ›”๏ธ --> <script src="index.js"></script> <div id="box"></div> </body> </html>

Because we placed the JS script tag above the div element, the index.js file is executed before the DOM element is created.

This means that we are unable to access the div in the index.js file.

index.js
const el = document.getElementById('box'); console.log(el); // ๐Ÿ‘‰๏ธ null const p = document.createElement('p'); // โ›”๏ธ Cannot read properties of null (reading 'appendChild') el.appendChild(p);

You have to place the JS script tag at the bottom of the body, after the DOM elements have been declared.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box"></div> <!-- โœ… GOOD - HTML is already available โœ… --> <script src="index.js"></script> </body> </html>

Now you can access the div element inside of the index.js file.

index.js
const el = document.getElementById('box'); console.log(el); // ๐Ÿ‘‰๏ธ div const p = document.createElement('p'); // โœ… works el.appendChild(p);

Conclusion #

The "Cannot read property 'appendChild' of null" error occurs when trying to call the appendChild method on a DOM element that doesn't exist.

To solve the error, make sure to only call the appendChild method on valid DOM elements.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee