Borislav Hadzhiev
Thu Oct 21 2021·2 min read
Photo by Guus Baggermans
The "Cannot read property 'offsetWidth' of null" error occurs for 2 reasons:
offsetWidth
property on a null
value (DOM element that
doesn't exist).Here is an example of how the error occurs.
const el = null; // ⛔️ Cannot read properties of null (reading 'offsetWidth') console.log(el.offsetWidth);
To solve the "Cannot read property 'offsetWidth' of null" error, make sure the
id you're using to get the element is contained in the DOM. The error often
occurs after providing a non-existent id
to the getElementById
method.
const el = document.getElementById('does-not-exist'); console.log(el); // 👉️ null // ⛔️ Cannot read properties of null (reading 'offsetWidth') console.log(el.offsetWidth);
We passed a non-existent id
to the getElementById
method and got a null
value back.
Accessing the offsetWidth
property on a null
value causes the error.
To solve the "Cannot read property 'offsetWidth' of null" error, place the JS script tag at the bottom of the body tag. The script should run after the DOM elements have been created.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- ⛔️ BAD - script runs before div exists ⛔️ --> <script src="index.js"></script> <div id="box">Text 1</div> </body> </html>
Notice that the JS script tag is placed above the HTML code that declares the
div
element.
The index.js
file is ran before the div
element is created, therefore we
can't access the div
in the file.
const el = document.getElementById('box'); console.log(el); // 👉️ null // ⛔️ Cannot read properties of null (reading 'offsetWidth') console.log(el.offsetWidth);
Instead, move the JS script tag to the bottom of the body, after the DOM elements you need to access.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">Text 1</div> <!-- ✅ GOOD - div already exists ✅ --> <script src="index.js"></script> </body> </html>
Now we can access the div
element inside the index.js
file.
const el = document.getElementById('box'); console.log(el); // 👉️ div#box // ✅ Works console.log(el.offsetWidth); // 👉️ 1653
offsetWidth
property rounds the value to an integer. If you need a fractional value, use the getBoundingClientRect()
method.The "Cannot read property 'offsetWidth' of null" error occurs when trying to
access the offsetWidth
property on a null
value.
To solve the error, run the JS script after the DOM elements are available and make sure you only access the property on valid DOM elements.