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

avatar

Borislav Hadzhiev

Sat Oct 23 20212 min read

banner

Photo by Elsie Zhong

Solve - Cannot read property 'clientWidth' of Null #

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

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