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.