Skip to main content

How to Resolve "TypeError: Cannot read properties of null (or undefined) reading 'style'" Error in JavaScript

The TypeError: Cannot read properties of null (reading 'style') and its close cousin ...of undefined (reading 'style') are among the most common errors in client-side JavaScript. Both errors mean the same thing: you are trying to access the .style property of a variable that does not hold a valid HTML element.

This guide will explain the crucial difference between null and undefined in this context, cover the two main causes of the error, and provide the standard, robust solutions to ensure your code runs at the right time.

Understanding the Error: null vs. undefined

Although both errors stop your script, they tell you slightly different things about why your variable isn't an element.

  • null: This is an intentional "no value" result. DOM methods like document.getElementById() will explicitly return null when they search the DOM and cannot find an element matching the selector.
  • undefined: This is the default state of a variable that has been declared but not assigned a value. It often occurs when you try to access an item from an array or collection that doesn't exist (e.g., the first item of an empty list).

In both cases, the root problem is the same: the variable is not a DOM element.

Problem Code (null)

const myElement = document.getElementById('non-existent-id');
console.log(myElement);
// Output: null

// ⛔️ Uncaught TypeError: Cannot read properties of null (reading 'style')
myElement.style.color = 'red';

Problem Code (undefined)

const elements = document.getElementsByClassName('non-existent-class');
console.log(elements); // Output: HTMLCollection [] (an empty, array-like object)

const firstElement = elements[0];
console.log(firstElement);
// Output: undefined

// ⛔️ Uncaught TypeError: Cannot read properties of undefined (reading 'style')
firstElement.style.color = 'red';

The Two Main Causes of the Error

Cause 1: The Selector is Incorrect

This is the simplest cause: a typo. Your JavaScript is trying to find an element that doesn't exist in your HTML because the ID or class name is wrong.

Example of error: HTML:

<div id="box-container"></div>

JavaScript:

// A typo: 'box-container' vs. 'box-conatiner'
const container = document.getElementById('box-conatiner');

// 'container' is null because the ID was wrong.
// ⛔️ Uncaught TypeError: Cannot read properties of null (reading 'style')
container.style.display = 'flex';

Cause 2: The Script Executes Before the DOM is Ready

This is the most common reason for the error. The browser parses HTML from top to bottom. If your <script> tag is in the <head> or at the top of the <body>, your code will run before the browser has created the HTML elements you're trying to select.

Example of error: HTML:

<!DOCTYPE html>
<html>
<head>
<!-- ⛔️ BAD: The script runs before the div exists in the DOM. -->
<script src="index.js"></script>
</head>
<body>
<div id="box">Hello World</div>
</body>
</html>

JavaScript (index.js):

const box = document.getElementById('box');

// The script runs, but the <body> has not been parsed yet, so the 'box' element cannot be found.
console.log(box);
// Output: null

// ⛔️ Uncaught TypeError: Cannot read properties of null (reading 'style')
box.style.color = 'blue';

Solutions

Solution 1: Move the <script> Tag to the End of the <body>

The simplest and most direct fix is to move your <script> tag to be the very last thing before the closing </body> tag.

Correct HTML Structure:

<!DOCTYPE html>
<html>
<body>
<div id="box">Hello World</div>

<!-- ✅ GOOD: By the time this script runs, all elements above it are in the DOM. -->
<script src="index.js"></script>
</body>
</html>

Now, when index.js executes, the div with the ID box is guaranteed to exist, and document.getElementById('box') will return the element correctly.

Solution 2: Use a DOMContentLoaded Event Listener (Best Practice)

A more robust and modern solution is to wrap your code in an event listener for the DOMContentLoaded event. This event fires as soon as the HTML document has been completely loaded and parsed, without waiting for stylesheets and images to finish loading.

This method allows you to keep your <script> tag in the <head> while ensuring your code only runs when it's safe to do so.

The Correct JavaScript:

// This script can be safely placed in the <head>
document.addEventListener('DOMContentLoaded', () => {
// All DOM manipulation code goes inside this function.
const box = document.getElementById('box');

// This code is guaranteed not to run until the DOM is ready.
console.log(box);
// Output: <div id="box">...</div>

// ✅ Works perfectly
box.style.color = 'blue';
});

Bonus Tip: Handling Collections of Elements

Remember that methods like getElementsByClassName and querySelectorAll return an HTMLCollection or a NodeList, not a single element. These are array-like objects. You must loop through them to apply styles to each element.

// Returns a collection, even if it only finds one element
const boxes = document.getElementsByClassName('box');

// You must iterate to style them.
for (const box of boxes) {
box.style.border = '1px solid green';
}

Conclusion

The Cannot read properties of null (or undefined) reading 'style' error is always a sign that your script is trying to manipulate a DOM element that it couldn't find.

To fix it, always ensure your script runs at the right time:

  1. Check your selectors: First, rule out any typos in your element IDs or class names.
  2. Move the <script> tag: The simplest fix is to place your <script> at the end of the <body>.
  3. Use an event listener (Best Practice): The most reliable solution is to wrap your DOM manipulation code in a DOMContentLoaded event listener.