TypeError: Cannot read properties of null (reading 'addEventListener')
Error message
Cannot read properties of null (reading 'addEventListener')
Quick summary
You tried to add an event listener to an element that does not exist in the DOM — the selector returned null.
Why this happens
The element ID or selector does not match any DOM element
The script ran before the DOM was fully loaded (element not yet present)
The element was dynamically removed before the listener was attached
Minimal example
const btn = document.querySelector("#nonexistent");
btn.addEventListener("click", () => {});const btn = document.querySelector("#nonexistent");
if (btn) btn.addEventListener("click", () => {});querySelector returns null when no element matches. Check for null before calling addEventListener.
How to diagnose
Log the element to confirm it is null
Check that the selector matches an element in the HTML
Verify the script runs after the DOM is loaded (use DOMContentLoaded or place script at end of body)
How to fix
Check for null before adding the listener: if (el) el.addEventListener(...)
Fix the selector to match the actual element
Move the script to the end of the body or use DOMContentLoaded event
How to prevent
Always check querySelector results before using them
Place scripts at the end of body or use defer/DOMContentLoaded
Use optional chaining: el?.addEventListener(...)
Related Resources
Related Glossary
Related Lessons
- DOM
Learn about DOM selection and events.