Categories
JavaScript Answers

How to fix “uncaught typeerror: cannot read properties of null (reading ‘addEventListener’)” error with JavaScript?

Spread the love

To fix "uncaught typeerror: cannot read properties of null (reading ‘addEventListener’)" error with JavaScript, we should make sure the element we’re calling addEventListener on isn’t null.

For instance, we write

const el = document.getElementById("overlayBtn");
if (el) {
  el.addEventListener("click", onClick, false);
}

to call getElementById to get the element we want to add the click listener to.

Then if el isn’t null, then we call addEventListener on it to add the onClick function as its click event listener.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *