Solve - Cannot set property 'width' of Null in JS

avatar

Borislav Hadzhiev

Last updated: Oct 19, 2021

banner

Check out my new book

Solve - Cannot set property 'width' of null #

The "Cannot set property 'width' of null" error occurs for 2 reasons:

  1. Setting the width property on a null value (DOM element that doesn't exist).
  2. Placing the JS script tag above the HTML where the DOM elements are declared.

cannot set property width of null

Here's an example of how the error occurs.

index.js
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 getElementById method.

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.

index.html
<!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 get the div from inside the index.js file.

Now, the index.js file has access to the div element.

index.js
const box = document.getElementById('box'); console.log(box); // 👉️ div#box // ✅ works box.style.width = '200px';

Conclusion #

The "Cannot set property 'width' of null" error occurs when trying to set the width property on a null value.

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.

Use the search field on my Home Page to filter through my more than 3,000 articles.