isotropic-2022
Share
Blog
Search
Menu

How To Fix Cannot Read Property 'style' of Null in JavaScript

By James LePage
|
Last updated on May 21st, 2022
|

One of the core goals of browser-based JavaScript is to add dynamic functionality to a web page by manipulating and modifying an HTML document. In doing so, it is often important to be able to also adjust the style of certain HTML elements. A common error you might run into while trying to do this is Uncaught TypeError: Cannot read properties of null (reading 'style'). Let’s fix it.

The Problem

You might have run into this error while trying to work with the style of an element in HTML:

error

This error boils down to one problem. The element you are trying to access does not exist in the DOM (document object model) for some reason or another. This could be because the DOM is not loaded before you tried to access the element, or there is a problem with how exactly you attempted to access it. Below you will find a few examples.

Accessing an element before it exists on the DOM

<!DOCTYPE html>
<html>
  <head></head>
  <script>
    document.getElementById("myDiv").style.color = "blue";
  </script>
  <div id="myDiv">
    <h1>hello world!</h1>
  </div>
</html>Code language: HTML, XML (xml)

In this example, the script is inserted before an element with id myDiv exists. In doing so the script will run before the element exists on the DOM and this causes the Cannot read properties of null error.

Incorrectly accessing an element

<!DOCTYPE html>
<html>
  <head></head>
  <div id="myDiv">
    <h1>hello world!</h1>
  </div>
  <script>
    document.getElementById("#myDiv").style.color = "blue";
  </script>
</html>Code language: HTML, XML (xml)

In the example above, the script is properly located in the HTML file but as you can see document.getElementById() is called using '#myDiv' which is incorrect for the element with id 'myDiv'. This also causes an error because no element with that given id exists. Similar issues can be caused by spelling mistakes or accidentally using getElementsByClassName() instead of getElementById() or vice versa. It may seem obvious at first but often times these are the easiest mistakes to make.

The Solution

Now that you have an idea of what may be causing your error, here are a few ways to resolve it.

Access an element only after it exists on the DOM

The simplest way to ensure you do not access the HTML element until after the DOM loads it is to include your script at the end of your HTML document. This will ensure that script’s code is not run until after the DOM loads.

<!DOCTYPE html>
<html>
  <head></head>
  <div id="myDiv">
    <h1>hello world!</h1>
  </div>
  <script>
    document.getElementById("myDiv").style.fontSize = "24px";
  </script>
</html>Code language: HTML, XML (xml)

If you want to be able to place your script anywhere you want — whether that is anywhere within this file or referenced anywhere in this file and defined elsewhere — you can add a listener for the DOMContentLoaded event.

document.addEventListener("DOMContentLoaded", function () {
  // your code here
});Code language: JavaScript (javascript)

Using this method will run a given callback only after the DOM loads. With the same example above, you can place your script in the head tag without encountering any errors:

<!DOCTYPE html>
<html>
  <head>
    <script>
      document.addEventListener("DOMContentLoaded", function () {
        document.getElementById("myDiv").style.fontSize = "24px";
      });
    </script>
  </head>
  <div id="myDiv">
    <h1>hello world!</h1>
  </div>
</html>Code language: HTML, XML (xml)

Properly access an element

Make sure the element you are trying to access has an id. In your document.getElementById() function call, make sure you type that id correctly and leave out the # in its name. If you wanted to use document.getElementByClassName() , make sure the given class name is also spelled properly and defined on the element(s) you want to access.

<!DOCTYPE html>
<html>
  <head></head>
  <div id="myDiv" class="myClass">
    <h1>hello world!</h1>
  </div>
  <script>
    document.getElementById("myDiv").style.color = "red";
    document.getElementsByClassName("myClass")[0].style.backgroundColor =
      "black";
  </script>
</html>Code language: HTML, XML (xml)

Conclusion

With your DOM loaded and your element access done properly, you will have resolved any Cannot read properties of null errors you may have received. If not, feel free to leave a comment and we will do our best to figure out what is going on in your situation. Thanks for reading!

The Isotropic Codex is a collection of code snippets and education for WordPress, web and WooCommerce developers.
References
Subscribe & Share
If you liked this content, subscribe for our monthly roundup of WordPress news, website inspiration, exclusive deals and interesting articles.
Unsubscribe at any time. We do not spam and will never sell or share your email.
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Rick Castle
Rick Castle
2 years ago

I find this blog very informative, keep up the good work.

Article By
James LePage
Contributors/Editors
notloggedin
James LePage is the founder of Isotropic, a WordPress education company and digital agency. He is also the founder of CodeWP.ai, a venture backed startup bringing AI to WordPress creators.
We're looking for new authors. Explore Isotropic Jobs.
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram