TypeError: Cannot read properties of null (reading 'addEventListener')
TypeError: null is not an object (evaluating 'x.name')
You’re trying to access a property or call a method on null. The variable exists but has no value.
Fix 1: DOM Element Not Found
// ❌ Element doesn't exist (yet)
const btn = document.getElementById('submit');
btn.addEventListener('click', handler); // 💥 btn is null
// ✅ Check if element exists
const btn = document.getElementById('submit');
if (btn) {
btn.addEventListener('click', handler);
}
// ✅ Or wait for DOM to load
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('submit').addEventListener('click', handler);
});
Fix 2: Script Loaded Before HTML
<!-- ❌ Script runs before the element exists -->
<script src="app.js"></script>
<button id="submit">Click</button>
<!-- ✅ Put script at the end or use defer -->
<button id="submit">Click</button>
<script src="app.js"></script>
<!-- Or use defer -->
<script defer src="app.js"></script>
Fix 3: API Returned Null
// ❌ Assuming API always returns data
const user = await fetchUser(id);
console.log(user.name); // 💥 If user is null
// ✅ Handle null response
const user = await fetchUser(id);
if (!user) {
console.log('User not found');
return;
}
console.log(user.name);
Fix 4: React — Ref Not Attached Yet
// ❌ Accessing ref before component mounts
const inputRef = useRef(null);
inputRef.current.focus(); // 💥 null on first render
// ✅ Use useEffect
useEffect(() => {
inputRef.current?.focus();
}, []);
Fix 5: Optional Chaining
// ❌ Deep property access
const city = user.address.city; // 💥 If address is null
// ✅ Optional chaining
const city = user?.address?.city ?? 'Unknown';
Fix 6: querySelector Returns Null
// ❌ Selector doesn't match anything
const el = document.querySelector('.nonexistent');
el.style.color = 'red'; // 💥 null
// ✅ Guard against null
const el = document.querySelector('.nonexistent');
if (el) el.style.color = 'red';