DOM Element is Null
Quick summary
Your JavaScript tries to access a DOM element that does not exist, resulting in 'Cannot read properties of null'.
Why this happens
The script runs before the DOM element is parsed
The selector does not match any element (typo, wrong class/id)
The element is dynamically added but the query runs before it is added
Minimal example
const el = document.querySelector(".nonexistent");
el.textContent = "Hello"; // TypeError: Cannot read properties of nullconst el = document.querySelector(".my-element");
if (el) {
el.textContent = "Hello";
} else {
console.warn("Element not found");
}Always check if the element exists before accessing its properties. Fix the selector if it is wrong, or ensure the script runs after the element is in the DOM.
How to diagnose
Check the error message — 'Cannot read properties of null' indicates a null element
Log the element: console.log(document.querySelector('.my-class')) — is it null?
Verify the selector matches an element in the HTML
How to fix
Move the script to the end of <body> or add defer
Wrap code in DOMContentLoaded event listener
Add a null check before accessing the element
Fix the selector to match the correct element
How to prevent
Use defer on scripts or place them at the end of <body>
Always check for null before using a queried element
Use event delegation for dynamically added elements
Related Resources
Related Lessons
- DOM Manipulation
Learn DOM manipulation.
Related Practice
- DOM Querying Concept
Practice DOM queries.