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

avatar

Borislav Hadzhiev

Last updated: Oct 23, 2021

banner

Photo from Unsplash

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

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

  1. Accessing the clientWidth property on a null value - a DOM element that doesn't exist.
  2. Inserting the JS script tag above the HTML, where the DOM elements are created.

cannot read property clientwidth of null

Here is an example of how the error occurs.

index.js
const el = null; // ⛔️ Uncaught TypeError: Cannot read properties of null (reading 'clientWidth') console.log(el.clientWidth);

To solve the "Cannot read property 'clientWidth' of null" error, make sure the id you're using to access the element exists. The error often occurs when an invalid id is passed to the getElementById method.

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

When an invalid id is passed to the getElementById method, we get a null value back. Accessing the clientWidth property on a null value throws the error.

To solve the "Cannot read property 'clientWidth' of null" error, insert the JS script tag at the bottom of the body tag, after the DOM elements have been created.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- ⛔️ BAD - index.js is run before div exists ⛔️ --> <script src="index.js"></script> <div id="box">Hello World</div> </body> </html>

The JS script tag is placed above the div element, therefore the div is not accessible inside of the index.js file.

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

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

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">Hello World</div> <!-- ✅ GOOD - div already exists ✅ --> <script src="index.js"></script> </body> </html>

Now you can access the div element inside of the index.js file.

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

Conclusion #

The "Cannot read property 'clientWidth' of null" error occurs when trying to access the clientWidth 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.