Solution To Fix: Cannot Read Property ‘Style’ Of Null In JavaScript

Cannot read property ‘style’ of Null in JavaScript

“Cannot read property ‘style’ of Null” in JavaScript is a standard error for newbies. It is also very easy to fix. Here are the reasons and how to fix them. Please read this article carefully.

Why does the error “Cannot read property ‘style’ of Null” in JavaScript happen?

There are many reasons for the above error to arise, but there are two common errors when this error line appears:

  • Accessing the style attribute of an element null
  • Run script tags before declaring HTML tags.

The error message occurs as follows:

Uncaught TypeError: Cannot read properties of null

How to fix this error?

Case 1: Accessing the style attribute of an element null 

Example:

var myCode = null;
console.log(myCode.style)

Output:

Uncaught TypeError: Cannot read properties of null

This error is often encountered when we use the getElementById() method and pass the parameter name of an id that does not exist in the DOM.

Example:

var el = document.getElementById('learn');
console.log(el);        
el.style.background = 'red'

Output:

Uncaught TypeError: Cannot read properties of null

At this point, your el will not exist, my second line of code will output null, so when we access el’s style, it will show an error.

To fix the this error, ensure that it is not null when accessing the style attribute of a declared DOM element.

Case 2: Running script tags before declaring HTML tags

This is common when we get the error “Cannot read property ‘style’ of Null” in JavaScript. To fix it, you must ensure the js code is running after the HTML snippets.

Example:

<!DOCTYPE html>
<html>
 <head>
    <meta charset="UTF-8" />
    <script>
	 var el = document.getElementById('demo');
     	 el.style.background = 'red'
    </script>
 </head>
 <body>
	<h1>LearnShareIT</h1>
    	<div id = "demo">LearnShareIT</div>
 </body>
</html>

Output: 

Uncaught TypeError: Cannot read properties of null

To fix it I would do the following:

<!DOCTYPE html>
<html>
 <head>
    <meta charset="UTF-8" />
 </head>
 <body>
	<h1>LearnShareIT</h1>
      <div id = "demo">LearnShareIT</div>
	<script>
	 var el = document.getElementById('demo');
        
       el.style.background = 'red'
	</script>
 </body>
</html>

As you can see, I have put the HTML code above the js code. When the page loads, the js code loads later and executes when the error is gone, and the program runs normally.

Summary

In this article, I solved the “Cannot read property ‘style’ of Null” error in JavaScript . To avoid encountering this error again, you can choose one of the solutions in above. Good luck!

Maybe you are interested:

Leave a Reply

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