Skip to main content

How to Resolve "TypeError: Cannot read properties of null (reading 'setAttribute')" in JavaScript

The TypeError: Cannot read properties of null (reading 'setAttribute') is a very common JavaScript error that occurs when you try to set an attribute on an HTML element that your script was unable to find. This error signals that your code is trying to perform an action on an object that doesn't exist, which is null.

This guide will explain the two main causes for this error: incorrect element selection and script execution timing. You will learn the simple, standard solutions to ensure your JavaScript code always runs after your HTML elements are ready.

Understanding the Error: What null Means

Let's break down the error message Cannot read properties of null (reading 'setAttribute').

  • It tried to call the function setAttribute.
  • It tried to call it on a value that was null.

This means that a line of your code looks like this: someVariable.setAttribute('attribute', 'value')

And at the time that line ran, the value of someVariable was null.

Example of code with error:

// This variable holds a value of null
const myElement = null;

// This is the line that causes the error, because myElement is null.
// ⛔️ Uncaught TypeError: Cannot read properties of null (reading 'setAttribute')
myElement.setAttribute('style', 'color: green;');

This error is the browser's way of telling you "You asked me to set an attribute on an HTML element, but I couldn't find that element.".

Cause 1: The DOM Element Does Not Exist (Incorrect Selector)

The most direct cause of this error is trying to select an element that isn't actually in your HTML. This is often due to a typo in an ID or class name.

Example of error: HTML:

<div id="box">Some text here.</div>

JavaScript:

// The ID 'my-box' does not exist in the HTML.
const boxElement = document.getElementById('my-box');

// The getElementById method couldn't find the element, so it returned null.
console.log(boxElement);
// Output: null

// Now, we try to use this null variable.
// ⛔️ Uncaught TypeError: Cannot read properties of null (reading 'setAttribute')
boxElement.setAttribute('hidden', 'true');

Because boxElement is null, the script fails the moment it tries to call .setAttribute() on it.

Cause 2: The Script is Executed Before the DOM Element is Created

This is the most common reason for this error. The browser parses and executes your HTML file from top to bottom. If your <script> tag is placed in the <head> or at the top of the <body>, your JavaScript code will execute before the browser has created the HTML elements in the DOM.

Example of error: HTML:

<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<!-- ⛔️ BAD: The script runs before the div element exists in the DOM. -->
<script src="index.js"></script>
</head>
<body>
<div id="box">Some text here.</div>
</body>
</html>

JavaScript (index.js):

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

// The script is running, but the browser has not parsed the <body> yet.
// Therefore, the element with the ID 'box' cannot be found.
console.log(boxElement);
// Output: null

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

Even though your selector is correct, the timing is wrong, resulting in the same null reference error.

Solution 1: Place Your <script> Tag at the End of the <body>

The simplest and most common solution is to move your <script> tag so it is the last item before the closing </body> tag.

The Correct HTML Structure:

<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<!-- All of your HTML elements come first. -->
<div id="box">Some text here.</div>

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

By the time the browser reaches and executes this script, all the HTML elements above it are guaranteed to exist, and your document.getElementById('box') call will successfully find the element and return it.

Solution 2: Use a DOMContentLoaded Event Listener

A more robust and modern solution is to keep your <script> in the <head> but wrap your code in an event listener. The DOMContentLoaded event fires only after all of the HTML has been parsed and the DOM is fully built.

This is the recommended best practice for professional web development as it cleanly separates your logic from your document structure.

The Correct JavaScript:

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

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

// ✅ Works perfectly
boxElement.setAttribute('style', 'color: red;');
});

Conclusion

The TypeError: Cannot read properties of null (reading 'setAttribute') error is almost always a timing issue related to the DOM loading process.

To fix it, you must ensure your script only runs after the target HTML element is available:

  1. Check your selectors: First, confirm there are no typos in your getElementById or other selector methods.
  2. Move the <script> tag: The easiest fix is to move your <script> tag to the end of the <body>.
  3. Use an event listener (Best Practice): The most reliable solution is to wrap your code in a DOMContentLoaded event listener, which guarantees the DOM is ready before your code executes.