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

avatar

Borislav Hadzhiev

Sat Oct 23 20212 min read

banner

Photo by Max Lakutin

Solve - Cannot read property 'clientHeight' of Null #

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

  1. Accessing the clientHeight property on a null value.
  2. Placing the JS script tag above the HTML, where the DOM elements are declared.
index.js
const el = null; // โ›”๏ธ Cannot read properties of null (reading 'clientHeight') console.log(el.clientHeight);

To solve the "Cannot read property 'clientHeight' of null" error, make sure you're using the correct id when getting the element. The error often occurs when providing a non-existent id to the getElementById method.

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

We passed a non-existent id to the getElementById method and got a null value back. Accessing the clientHeight property on a null value causes the error.

To solve the "Cannot read property 'clientHeight' 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> <!-- โ›”๏ธ BAD - script is ran before div exists โ›”๏ธ --> <script src="index.js"></script> <div id="box">Text</div> </body> </html>

Because we placed the JS script above the div element, the script is ran before the div element is created, therefore the index.js file cannot access the div element.

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

Instead, place the JS script at the bottom of the body tag.

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

Now we can access the div element inside the index.js file.

index.js
const el = document.getElementById('box'); console.log(el); // ๐Ÿ‘‰๏ธ div#box // โœ… Works console.log(el.clientHeight); // ๐Ÿ‘‰๏ธ 18

Conclusion #

The "Cannot read property 'clientHeight' of null" error occurs when trying to access the clientHeight property on a null value.

To solve the error, make sure the JS script tag is loaded after the HTML is declared and the id of the element exists in the DOM.

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