TypeError: Cannot read property 'insertBefore' of Null in JS

avatar

Borislav Hadzhiev

Last updated: Oct 21, 2021

banner

Photo from Unsplash

TypeError: Cannot read property 'insertBefore' of Null in JS #

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

  1. Calling the insertBefore method on a null value (DOM element that doesn't exist).
  2. Inserting the JS script tag above the HTML where the DOM elements are declared.

cannot read property insertbefore of null

Here is an example of how the error occurs.

index.js
const parent = document.getElementById('does-not-exist'); console.log(parent); // 👉️ null const child = document.getElementById('child-2'); const newNode = document.createElement('span'); // ⛔️ Uncaught TypeError: Cannot read properties of null (reading 'insertBefore') parent.insertBefore(newNode, child);

We passed a non-existent id to the getElementById method, so the method returned null. Calling the insertBefore() method on a null value causes the error.

To solve the "Cannot read property 'insertBefore' of null" error, place the JS script tag at the bottom of the body tag, after the DOM elements have been declared.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box"> <span id="child-2">Span 2</span> </div> <!-- ✅ GOOD - div elements already exist ✅ --> <script src="index.js"></script> </body> </html>

Notice that the JS script tag is at the bottom of the body. This means that we can access the div element inside of our index.js file.

Had we placed the JS script above the declaration of the HTML elements, the script would be ran before the elements are created.

index.js
const parent = document.getElementById('box'); const child = document.getElementById('child-2'); const newNode = document.createElement('span'); // ✅ Works const result = parent.insertBefore(newNode, child); console.log(result); // 👉️ span

Conclusion #

The "Cannot read property 'insertBefore' of null" error occurs when trying to call the insertBefore() method on a null value.

To solve the error, place the JS script tag after the DOM elements are declared and make sure you only call the method on valid DOM elements.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.