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

avatar

Borislav Hadzhiev

Last updated: Oct 23, 2021

banner

Photo from Unsplash

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

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.

cannot read property clientheight of null

Here is an example of how the error occurs.

index.js
const el = null; // ⛔️ Uncaught TypeError: 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 run 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 run 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.

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.