Last updated: Oct 19, 2021
Check out my new book
The "Cannot set property 'width' of null" error occurs for 2 reasons:
widthproperty on a
nullvalue (DOM element that doesn't exist).
Here's an example of how the error occurs.
const box = null; // ⛔️ Cannot set properties of null (setting 'width') box.width = '200px';
Make sure the
id you're using to access the element exists in the DOM. The
error often occurs after providing a non-existent
id to the
To solve the "Cannot set property 'onclick' 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> <div id="box" style="background-color: blue; height: 100px; width: 100px" ></div> <!-- ✅ GOOD - div already exists ✅ --> <script src="index.js"></script> </body> </html>
Note that the JS script tag is placed at the bottom of the body tag, after all of the DOM elements it needs access to.
Had we placed the JS script tag above the
div element, we wouldn't be able to
div from inside the
index.js file has access to the
const box = document.getElementById('box'); console.log(box); // 👉️ div#box // ✅ works box.style.width = '200px';
The "Cannot set property 'width' of null" error occurs when trying to set the
width property on a
To solve the error, run the JS script after the DOM elements are available and make sure you only set the property on valid DOM elements.