How to fix error cannot read property of style null

If you have ever received the error following error:

cannot read property of style null

It can be frustrating to debug as the solution can vary depending on the situation.

So, how can you fix cannout read property of style null? It’s likely that this error referring to an undefined document.

We should ensure that the document is defined before trying to access the style property.

Here are some potential fixes.

Checking for null

If a null error is blocking our website’s JavaScript we can simply check if our element is defined.

const header = document.querySelector("h1");
if (header) {
  header.style.color = "orange";
}

We will avoid this error altogether as header will need to be available to change its style.

Moving script before Body

While checking for null will fix our web page, this doesn’t solve the actual reason why the document might be undefined.

To fully diagnose an issue like this, it’s important to pinpoint the reasons why an element reference is null. It is worth examining if the document has been readily loaded before trying to access anything in it.

Let say we have the following script:

<head>
 <script> 
    const header = document.querySelector("h1");
    header.style.color = 'orange';
 </script>
<head>

Let’s take this script our of the head altogether and make sure that it is called before the end of </body> instead.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
</head>

<body>
    <h1>Test Name</h1>
  <script> 
    const header = document.querySelector("h1");
	header.style.color = 'orange';
  </script>
</body>
</html>

As you can see, our DOM will be ready to manipulate by the time our script is executed.  I hope this helped.

Gareth Dunne

Senior JavaScript Engineer and creator of JSdiaries. Passionate about the latest in web technologies and how it can provide value for my clients.