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

avatar

Borislav Hadzhiev

Thu Oct 21 20212 min read

Solve - Cannot read property 'insertBefore' of Null #

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.
index.js
const parent = document.getElementById('does-not-exist'); console.log(parent); // 👉️ null const child = document.getElementById('child-2'); const newNode = document.createElement('span'); // ⛔️ 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 executed 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.

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