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

avatar

Borislav Hadzhiev

Last updated: Oct 23, 2021

banner

Photo from Unsplash

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

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

  1. Accessing the children property on a non-existent DOM element.
  2. Inserting the JS script tag above the HTML where the DOM elements are created.

cannot read property children of null

Here is an example of how the error occurs.

index.js
const el = null; // ⛔️ TypeError: Cannot read properties of null (reading 'children') const collection = el.children;

To solve the "Cannot read property 'children' of null" error, make sure to provide a valid id when getting the DOM element. The error commonly occurs when an invalid id is provided to the getElementById method.

index.js
const el = document.getElementById('does-not-exist'); console.log(el); // 👉️ null // ⛔️ Cannot read properties of null (reading 'children') const collection = el.children;

Because we passed an invalid id to the getElementById method, we go a null value back. Accessing the children property on a null value causes the error.

To solve the "Cannot read property 'children' of null" error, make sure to insert the JS script tag at the bottom of the body tag. The JS script should be ran after the DOM elements have been created.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- ⛔️ BAD - script is run before divs are created ⛔️ --> <script src="index.js"></script> <div id="box"> <div id="content">Test</div> </div> </body> </html>

Notice that the index.js script is run before the div elements are created. This means that the div elements will not be accessible inside the index.js file.

index.js
const el = document.getElementById('box'); console.log(el); // 👉️ null // ⛔️ Cannot read properties of null (reading 'children') const collection = el.children;

You should place the JS script tag at the bottom of the body, after the DOM elements.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box"> <div id="content">Test</div> </div> <!-- ✅ GOOD - div elements are already created ✅ --> <script src="index.js"></script> </body> </html>

Now the div elements can be accessed inside the index.js file.

index.js
const el = document.getElementById('box'); console.log(el); // 👉️ div#box // ✅ Works const collection = el.children; console.log(collection); // 👉️ HTMLCollection

Conclusion #

The "Cannot read property 'children' of null" error occurs when accessing the children property on a null value.

To solve the error, make sure to only access the children property 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.