🔧 Error Fixes
· 1 min read

TypeError: Cannot Read Properties of Null — How to Fix It (Vanilla JS)


Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
Uncaught TypeError: Cannot read properties of null (reading 'style')
Uncaught TypeError: Cannot read properties of null (reading 'value')

This means you’re trying to use an element that doesn’t exist. document.querySelector() or document.getElementById() returned null, and you’re trying to do something with it.

Fix 1: Your script runs before the DOM is ready

The most common cause. Your <script> tag is in the <head>, so it runs before the HTML elements exist.

<!-- ❌ Script runs before the button exists -->
<head>
  <script>
    document.getElementById('btn').addEventListener('click', ...);
  </script>
</head>
<body>
  <button id="btn">Click me</button>
</body>

Fix — move script to bottom of body:

<body>
  <button id="btn">Click me</button>
  <script>
    document.getElementById('btn').addEventListener('click', ...);
  </script>
</body>

Or use defer:

<head>
  <script src="app.js" defer></script>
</head>

Or wrap in DOMContentLoaded:

document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('btn').addEventListener('click', ...);
});

Fix 2: Typo in the selector

// ❌ ID doesn't match
document.getElementById('buton')  // typo: "buton" vs "button"

// ❌ Missing # in querySelector
document.querySelector('btn')     // should be '#btn'

// ✅ Correct
document.getElementById('btn')
document.querySelector('#btn')

Fix 3: Element is conditionally rendered

The element might not exist on every page:

// ❌ Crashes if #admin-panel doesn't exist on this page
document.getElementById('admin-panel').style.display = 'block';

// ✅ Check first
var panel = document.getElementById('admin-panel');
if (panel) {
  panel.style.display = 'block';
}

Fix 4: Wrong scope with querySelectorAll

// ❌ querySelectorAll returns a NodeList, not a single element
var items = document.querySelectorAll('.item');
items.style.color = 'red';  // TypeError!

// ✅ Loop through the list
document.querySelectorAll('.item').forEach(function(item) {
  item.style.color = 'red';
});