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

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.