Categories
JavaScript Answers

How to fix Cannot read property ‘addEventListener’ of null with JavaScript?

Spread the love

Sometimes, we want to fix Cannot read property ‘addEventListener’ of null with JavaScript.

In this article, we’ll look at how to fix Cannot read property ‘addEventListener’ of null with JavaScript.

How to fix Cannot read property ‘addEventListener’ of null with JavaScript?

To fix Cannot read property ‘addEventListener’ of null with JavaScript, we should make sure we’re calling addEveentListener on an element.

For instance, we write

const el = document.getElementById("overlayBtn");

if (el) {
  el.addEventListener("click", onClick, false);
}

to select an element with ID overlayBtn with getElementById.

Then we use an if statement to check if el is truthy.

If it is, then we call addEventListener on it since it’s an element if it’s not null.

Conclusion

To fix Cannot read property ‘addEventListener’ of null with JavaScript, we should make sure we’re calling addEveentListener on an element.

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 *