Categories
JavaScript Answers

How to fix the “cannot read properties of undefined (reading ‘style’)” error with JavaScript?

Spread the love

To fix the "cannot read properties of undefined (reading ‘style’)" error with JavaScript, we should make sure the element we’re selecting isn’t null.

For instance, we write

const boxElement = document.querySelector(".box");
if (boxElement) {
  boxElement.style.width = "100px";
  boxElement.style.height = "100px";
  boxElement.style.backgroundColor = "#f00";
}

to select the element with the class box with querySelector.

Then if boxElement isn’t null, then we set its width, height and backgroundColor styles to apply the style values we want.

If the element isn’t null, then the style property should always be an object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *