Ошибка addeventlistener is not a function

I’m getting an «.addEventListener is not a function» error. I am stuck on this:

var comment = document.getElementsByClassName("button");
function showComment() {
  var place = document.getElementById('textfield');
  var commentBox = document.createElement('textarea');
  place.appendChild(commentBox);
}
comment.addEventListener('click', showComment, false);
<input type="button" class="button" value="1">
<input type="button" class="button" value="2">
<div id="textfield">
</div>

agrm's user avatar

agrm

3,7354 gold badges26 silver badges36 bronze badges

asked Aug 15, 2015 at 18:28

leecarter's user avatar

3

The problem with your code is that the your script is executed prior to the html element being available. Because of the that var comment is an empty array.

So you should move your script after the html element is available.

Also, getElementsByClassName returns html collection, so if you need to add event Listener to an element, you will need to do something like following

comment[0].addEventListener('click' , showComment , false ) ; 

If you want to add event listener to all the elements, then you will need to loop through them

for (var i = 0 ; i < comment.length; i++) {
   comment[i].addEventListener('click' , showComment , false ) ; 
}

answered Aug 15, 2015 at 18:30

Nikhil Aggarwal's user avatar

Nikhil AggarwalNikhil Aggarwal

28.2k4 gold badges43 silver badges59 bronze badges

1

document.getElementsByClassName returns an array of elements. so may be you want to target a specific index of them: var comment = document.getElementsByClassName('button')[0]; should get you what you want.

Update #1:

var comments = document.getElementsByClassName('button');
var numComments = comments.length;

function showComment() {
  var place = document.getElementById('textfield');
  var commentBox = document.createElement('textarea');
  place.appendChild(commentBox);
}

for (var i = 0; i < numComments; i++) {
  comments[i].addEventListener('click', showComment, false);
}

Update #2: (with removeEventListener incorporated as well)

var comments = document.getElementsByClassName('button');
var numComments = comments.length;

function showComment(e) {
  var place = document.getElementById('textfield');
  var commentBox = document.createElement('textarea');
  place.appendChild(commentBox);
  for (var i = 0; i < numComments; i++) {
    comments[i].removeEventListener('click', showComment, false);
  }
}

for (var i = 0; i < numComments; i++) {
  comments[i].addEventListener('click', showComment, false);
}

Aldo D'Aquino's user avatar

answered Aug 15, 2015 at 18:30

Tahir Ahmed's user avatar

Tahir AhmedTahir Ahmed

5,6872 gold badges17 silver badges28 bronze badges

8

var comment = document.getElementsByClassName("button");

function showComment() {
  var place = document.getElementById('textfield');
  var commentBox = document.createElement('textarea');
  place.appendChild(commentBox);
}

for (var i in comment) {
  comment[i].onclick = function() {
    showComment();
  };
}
<input type="button" class="button" value="1">
<input type="button" class="button" value="2">
<div id="textfield"></div>

Zoe's user avatar

Zoe

27.1k21 gold badges119 silver badges148 bronze badges

answered Dec 22, 2017 at 12:05

antelove's user avatar

anteloveantelove

3,22626 silver badges20 bronze badges

The first line of your code returns an array and assigns it to the var comment, when what you want is an element assigned to the var comment…

var comment = document.getElementsByClassName("button");

So you are trying to use the method addEventListener() on the array when you need to use the method addEventListener() on the actual element within the array. You need to return an element not an array by accessing the element within the array so the var comment itself is assigned an element not an array.

Change…

var comment = document.getElementsByClassName("button");

to…

var comment = document.getElementsByClassName("button")[0];

answered Jun 8, 2018 at 21:11

DreamBird's user avatar

DreamBirdDreamBird

511 silver badge2 bronze badges

Another important thing you need to note with «.addEventListener is not a function» error is that the error might be coming a result of assigning it a wrong object eg consider

let myImages = ['images/pic1.jpg','images/pic2.jpg','images/pic3.jpg','images/pic4.jpg','images/pic5.jpg'];
let i = 0;
while(i < myImages.length){
  const newImage = document.createElement('img');
  newImage.setAttribute('src',myImages[i]);
  thumbBar.appendChild(newImage);

 //Code just below will bring the said error 
 myImages[i].addEventListener('click',fullImage);

 //Code just below execute properly 
  newImage.addEventListener('click',fullImage);




  i++;
}

In the code Above I am basically assigning images to a div element in my html dynamically using javascript. I’ve done this by writing the images in an array and looping them through a while loop and adding all of them to the div element.

I’ve then added a click event listener for all images.

The code «myImages[i].addEventListener(‘click’,fullImage);» will give you an error of «addEventListener is not a function» because I am chaining an addEventListener to an array object which does not have the addEventListener() function.

However for the code «newImage.addEventListener(‘click’,fullImage);» it executes properly because the newImage object has access the function addEventListener() while the array object does not.

For more clarification follow the link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_a_function

answered Apr 9, 2020 at 5:33

MosesK's user avatar

MosesKMosesK

3593 silver badges7 bronze badges

The main reason of this error is this line

document.getElementsByClassName("button")

Cause the getElementsByClassName returns an array-like object of all child elements or a collection of elements.

There are two possible solutions AFAIK —

  1. Treat the variable containing document.getElementsByClassName("button") as an array and be specific when using an event listener.
    Example —

    comment[0].addEventListener('click' , showComment , false )

  2. Use id for selecting that specific element.
    Example-

    document.getElementById('button')

answered Oct 23, 2022 at 13:59

Mohammad Mustak Absar Khan's user avatar

Try this one:

var comment = document.querySelector("button");
function showComment() {
  var place = document.querySelector('#textfield');
  var commentBox = document.createElement('textarea');
  place.appendChild(commentBox);
}
comment.addEventListener('click', showComment, false);

Use querySelector instead of className

Nick's user avatar

Nick

139k22 gold badges57 silver badges95 bronze badges

answered May 19, 2018 at 12:38

midnightgamer's user avatar

midnightgamermidnightgamer

4441 gold badge5 silver badges18 bronze badges

If you want to target multiple buttons and add a event listener to all you need to first target all buttons and after use loop for each button

const buttons = document.querySelectorAll(".btn");

buttons.forEach((button)=>{

button.addEventListener("click",()=>{
    console.log("clicked")
})

})

answered Apr 26 at 14:47

ankit jha's user avatar

<script src="main.js" defer></script>

which makes execute your code after the document fully loaded hence the javascript has complete reference

answered Oct 14, 2022 at 9:51

Marimuthu's user avatar

1

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.

When running JavaScript code, you might encounter the error below:

TypeError: addEventListener is not a function

This error occurs when you call the addEventListener() method from an object that doesn’t know about the method.

Most likely, you’re calling the method not from an Element object but from an array instead.

Let’s see an example that causes this error and how to fix it in practice.

How to reproduce the error

Suppose you have an HTML document with the following content:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Nathan Sebhastian</title>
  </head>

  <body>
    <div class="reg">Line 1</div>
    <div class="reg">Line 2</div>
    <div class="reg">Line 3</div>
  </body>
</html>

Next, you run the following JavaScript code in a <script> tag:

const divEl = document.getElementsByClassName("reg");

divEl.addEventListener("click", function onClick() {
  alert("line clicked");
});

But when running the code above, you get the following error:

Uncaught TypeError: divEl.addEventListener is not a function

The error happens because the getElementsByClassName() method returns an HTMLCollection array object no matter if there’s any matching Element object or not.

You can’t call the addEventListener() method from the returned array. You need to iterate over the array using the for .. of loop like this:

const divEl = document.getElementsByClassName("reg");

for (const element of divEl) {
  element.addEventListener("click", function onClick() {
    console.log("line clicked");
  });
}

Here, the for .. of loop will iterate over the returned divEl array and attach an event listener to each Element object.

If you want to add an event listener only to a specific element in the array, you can access the individual object using the index notation.

The example below shows how to add the event listener only to the ‘Line 2’ element:

const divEl = document.getElementsByClassName("reg");

divEl[1].addEventListener("click", function onClick() {
  console.log("line clicked");
});

Here, we accessed a specific element with divEl[1] to attach the event listener. Because it’s a valid Element object, the code runs without any error.

The following JavaScript selector methods return an array, so the addEventListener is not a function error would likely occur when you use any one of these:

  • getElementsByClassName()
  • getElementsByName()
  • getElementsByTagName()
  • querySelectorAll()

While these selector methods return a valid Element object or null when not found:

  • getElementById()
  • querySelector()

Knowing the different return values between the selector methods should help you prevent the error from happening in the first place.

Also note that JavaScript methods are case-sensitive, which means you need to type the method exactly as addEventListener and not addeventlistener.

I hope this tutorial helps you fix the error. Happy coding! 👍

var skin1 = document.getElementsByClassName("skin_1");
skin1.addEventListener("click", function(){
        console.log("hi");
});


  • Вопрос задан

  • 2421 просмотр

Потому что skin1 в данном случаем возвращает массив.

Делайте так:

var skin1 = document.getElementsByClassName("skin_1");
for (var i=0 ; i<skin1.length; i++) {
  skin1[i].addEventListener("click", function(){
          console.log("hi");
  });
}

Вероятно потому, что getElementsByClassName возвращает список элементов, а не одиночный элемент?

Пригласить эксперта

Присоединюсь.
getElementsByClassName — возвращает коллекцию (массив).
Ознакомьтесь с пруфами 1, 2

Дополню.
Возможно addEventListener лучше не использовать, т.к. может повесится несколько обработчиков делающих одно и то же. Если заметите, что клик срабатывает несколько раз, перепишите на onclick

Мне помогла замена на такой код:

$(document).ready(function() {
    document.addEventListener( 'wpcf7submit', function( event ) {
        if ( '148' == event.detail.contactFormId ) { // Замените id на свою форму
            alert( "Опачки, меня пытаются отправить... в Магадан!" );
        }
    }, false );
});


  • Показать ещё
    Загружается…

22 сент. 2023, в 13:33

60000 руб./за проект

22 сент. 2023, в 13:26

300000 руб./за проект

22 сент. 2023, в 13:21

100 руб./за проект

Минуточку внимания

SitePoint Forums | Web Development & Design Community

Loading

Понравилась статья? Поделить с друзьями:
  • Ошибка addon sauerland requires addon chernarus
  • Ошибка additemmenu dll не обнаружен
  • Ошибка addin scaner45
  • Ошибка add стиральная машина miele
  • Ошибка add toner