Skip to content

How to Fix Cannot read properties of null (reading 'X') in JavaScript

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about How to Fix Cannot read properties of null (reading 'X') in JavaScript. We cover key concepts, practical examples, and best practices.

The Problem

JavaScript throws TypeError: Cannot read properties of null (reading 'X') when document.querySelector() or similar DOM methods return null because the element does not exist or the script runs before the DOM is ready.

Quick Fix

Step 1: Check if the element exists

Always verify the element exists before accessing its properties:

const button = document.querySelector('#submit-btn');
button.addEventListener('click', handleSubmit);
TypeError: Cannot read properties of null (reading 'addEventListener')

Add a null check:

const button = document.querySelector('#submit-btn');
if (button) {
    button.addEventListener('click', handleSubmit);
} else {
    console.warn('Button element not found');
}

Step 2: Wait for the DOM to load

Scripts in the <head> run before the DOM is parsed:

document.querySelector('.header').style.color = 'red';
TypeError: Cannot read properties of null (reading 'style')

Wait for DOMContentLoaded:

document.addEventListener('DOMContentLoaded', () => {
    document.querySelector('.header').style.color = 'red';
});

Or move the <script> tag to the end of <body>.

Step 3: Verify the selector

A typo in the selector returns null:

const el = document.querySelector('my-class');
console.log(el.textContent);
TypeError: Cannot read properties of null (reading 'textContent')

Use the correct selector syntax:

const el = document.querySelector('.my-class');
if (el) {
    console.log(el.textContent);
}

Step 4: Check for dynamic content

If the element is added by JavaScript after page load, wait for it:

function waitForElement(selector, callback) {
    const el = document.querySelector(selector);
    if (el) {
        callback(el);
        return;
    }
    const observer = new MutationObserver(() => {
        const found = document.querySelector(selector);
        if (found) {
            callback(found);
            observer.disconnect();
        }
    });
    observer.observe(document.body, { childList: true, subtree: true });
}
waitForElement('.dynamic-content', (el) => {
    el.textContent = 'Found it!';
});

Prevention

  • Always check for null after DOM queries.
  • Move scripts to the end of <body> or use defer.
  • Use optional chaining: document.querySelector('.x')?.textContent.
  • Wait for dynamic elements using MutationObserver.
  • Use TypeScript with strict null checks to catch these at compile time.

Common Mistakes with dom not found

  1. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  2. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  3. Misunderstanding that String is [Char] with poor performance for large text operations

These mistakes appear frequently in real-world JS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Why does querySelector return null for a valid selector?

The element may not exist in the DOM yet (script runs too early), the selector syntax is wrong (missing . for class or # for id), or the element is inside a shadow DOM. Always check that the element is present in the HTML source and that the selector matches exactly.

What is the difference between null and undefined in this error?

null means the DOM query explicitly found nothing (the element does not exist). undefined means a variable has not been assigned. The error message tells you which one you are dealing with, which helps narrow down the cause.

Can I use optional chaining to avoid null errors on DOM elements?

Yes. document.querySelector('.my-class')?.textContent returns undefined instead of throwing if the element is not found. This is useful for optional elements where a missing element is an expected case rather than an error.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro