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

avatar

Borislav Hadzhiev

Sat Oct 23 20212 min read

banner

Photo by Jamie Street

Solve - Cannot read property 'children' of Null #

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.
index.js
const el = null; // โ›”๏ธ 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 ran 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 executed 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.

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