How to fix - addEventListener is not a function

Common causes of the 'addEventListener is not a function' error in JavaScript and the guide to fix this.

Jul 1, 2023 | Read time 8 minutes

🔔 Table of contents

Introduction

We get the error “addEventListener is not a function” because the element we are targeting is not a DOM element and does not support interactive events.

Some reasons why this error comes up is usually because we are using the function/syntax incorrectly, the element has not exist yet, we are targeting the wrong element or even that the object does not support interactivity.

I came across this error recently with one of my web designs! I was trying to add a alert when someone clicks on a button. Now after a bit of clicking - nothing happened!!

Looking deeper in the browser console, I found that this error “addEventListener is not a function” popped up.

I will go over the ways that I troubleshooted and fixed this error.

Generally, the steps are:

  1. Verify that you got the syntax right
  2. Check that the element exists
  3. Make sure that DOM is ready
  4. Check if addEventListener is added to “Element” object
  5. getElementsByClassName() and querySelectorAll() issues

1. Verify that you got the syntax right

Now before we do anything, we want to make sure that we are calling the addEventListener() function correctly.

Here’s an example of using addEventListener():

document.querySelector("#myButton").addEventListener("click", function(event) {
    console.log("Button was clicked!");
});

The above code just attaches addEventLister to a button (#myButton) and when the user clicks on the button, it will log to the browser console:

“Button was clicked”

Generally the addEventListener() method has three parameters:

  • Event Type - this a string that represents the event we want to attach to - eg ‘click’, ‘blur’, etc. Now this is required when calling the addEventListener function.
    As an example example - If we want to run some code when the user clicks a particular element, we can use “click”.

Other examples include ‘submit’, ‘keydown’, ‘keyup’, ‘mouseover’, etc.

Tip: Keep in mind of case-sensitivity

Make sure that you are not having any typos and check for casing. “Click” is different to “click” - with the former being invalid.

  • Listener function - this is required. This function will run every time the event (eg - click, mouseover, etc) triggers. Keep in mind that we are passing the function reference and not the function execution.

So for example if you want to run a function addItem we should only pass the function without the brackets ():

...addEventListener("click", addItem); // ✔️ passing the function reference

...addEventListener("click", addItem()); // ❌ wrong since we are running the function
  • The third parameter is the capture which is optional. It is a Boolean indicating whether events of this type will be dispatched to the registered listener before reaching any other EventTarget beneath it in the DOM tree.

The default value is false, which means that the event bubbles up from the target.

If true, the event is captured and goes down from the top of the document to the target.

2. Check that the element exists

Typically the most common reason why “addEventListener is not a function” error comes up is that the element does not exist.

We want to make sure that we are targeting the right element and that it will exist.

Consider the following piece of code:

var myElement = document.getElementById("nonexistentId");
myElement.addEventListener("click", function() {
  console.log("Clicked");
});

In this example, if there’s no element with the ID “nonexistentId”, then “myElement” is null and you can’t add an event listener to null.

3. Make sure that DOM is ready

One thing to make sure is to run the addEventListener function after the DOM has loaded. This is usually with the “DOMContentLoaded” event:

document.addEventListener("DOMContentLoaded", function() {
  var myElement = document.getElementById("myId");
  myElement.addEventListener("click", function() {
    console.log("Clicked");
  });
});

This will ensure that the DOM is fully loaded before we try to add a event listener to the “myElement” DOM object.

4. Check if addEventListener is added to “Element” object

The next common reason why this error occurs is that the addEventListener method is “Element” objects that can accept interactive events.

If you’re trying to use it on something that isn’t a DOM object (like a plain old JavaScript object, or undefined), you’ll get this error.

You can use addEventListener on any object that is a Node in the DOM, including elements (objects of class Element), the document object itself, and even the window object.

Here’s an example of correct usage:

document.getElementById('myButton').addEventListener('click', function() {
    console.log('Button was clicked!');
});

However, if you attempt to use addEventListener on a plain JavaScript object, or on other non-DOM objects, it won’t work because those objects don’t have an addEventListener method. Here’s an example:

let myObject = {};
myObject.addEventListener('click', function() {
    console.log('This will not work');
});

In this case, you’ll get the error myObject.addEventListener is not a function, because addEventListener is not a function that’s available on plain JavaScript objects.

5. getElementsByClassName() and querySelectorAll() issues

A common problem that I have found is using the getElementsByClassName and querySelectorAll functions and then trying to add event handlers to them.

So for example, if we do this - we will get an error:

document.getElementsByClassName("button").addEventListener('click', function() {
    console.log('This will not work');
});

Now if we look closely at the getElementsByClassName and querySelectorAll functions, we can see that they return a list of DOM objects. However, addEventListener only accepts ONE Element object.

If you’re using document.querySelectorAll or similar to get a collection of elements, you’ll need to loop through each one and add the event listener individually.

var buttons = document.querySelectorAll("button");
for(var i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener("click", function() {
    console.log("Button clicked");
  });
}

This way, we are using addEventListener as it was intended for ONE element!

Tips for using addEventListener

  • Make sure to call removeEventListener when you are finished with the handler
  • the “event type” is case-sensitive - so a click event is represented by “click” and not “Click” (with upper casing)

Summary

In this post, I went over how to fix the “addEventListener is not a function”. This error comes up when we are trying to attach an event handler to a non-DOM object that does not accept interactive events.

To fix this we go through our checklist:

  1. Having the right the syntax to call addEventListener - which takes a case-sensitive string and a function reference
  2. Make sure that the element exists in the first place or we will be calling to a null object
  3. Make sure that DOM is ready
  4. Check if addEventListener is added to “Element” object. Non-DOM elements such as Javascript objects will not have this function.
  5. getElementsByClassName() and querySelectorAll() returns a list of DOM objects so you will need to loop through them to attach a event handler.

👋 About the Author

G'day! I am Huy a software engineer based in Australia. I have been creating design-centered software for the last 10 years both professionally and as a passion.

My aim to share what I have learnt with you! (and to help me remember 😅)

Follow along on Twitter , GitHub and YouTube