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';
});
Related resources
Related: Syntax Error Unexpected Token Fix Β· Sveltekit Load Error Fix