How to Fix Cannot read properties of null (reading 'X') in JavaScript
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 usedefer. - 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
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro