Common causes
- document.getElementById() or querySelector() returned null because the element doesn't exist
- A database query returned null for a record that wasn't found
- JSON.parse() parsed a 'null' literal string
- A function explicitly returns null to indicate 'no result'
How to fix it
- Check for null before accessing properties: if (element !== null)
- Use optional chaining: element?.textContent
- For DOM elements, ensure the element exists in the HTML before the script runs
- Add fallback values: const result = getValue() ?? defaultValue
Example
TypeError: Cannot read properties of null (reading 'addEventListener')
at HTMLDocument.<anonymous> (/home/user/app.js:5:40)Calling addEventListener on document.getElementById('btn') where no element with id 'btn' exists in the HTML
Have a different error?
Paste any error message into the Error Translator to get an instant explanation.
