Js addeventlistener ошибка

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,7244 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.1k4 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 stands with Ukraine's user avatar

answered Dec 22, 2017 at 12:05

antelove's user avatar

anteloveantelove

3,10025 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

3493 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

138k22 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

The “cannot read property ‘addEventListener’ of null” error occurs in JavaScript when you try to call the addEventListener() method on an element that cannot be found in the DOM. This happens for two main reasons:

  1. Accessing the addEventListener() method on an element absent from the DOM.
  2. Inserting the script tag referencing the JavaScript file at a point above the declaration of the DOM element in the HTML.

We’ll learn how to handle the error for these two scenarios in this article.

The "cannot read property 'addEventListener' of null" error occurring in JavaScript.

Cause 1: Accessing addEventListener() on an element not present in the DOM

index.js

const btn = document.getElementById('does-not-exist');

console.log(btn); // null

// ❌ Cannot read property 'addEventListener' of null
btn.addEventListener('click', () => {
  alert('You clicked the button');
});

When a method like getElementById() or querySelector() method is used to search for an element that doesn’t exist in the DOM, it returns null. And attempting to call the addEventListener() method on a null value will cause the error.

Solve: Ensure correct selector

To fix the “cannot read property ‘addEventListener’ of null” error, make sure the selector used the access the element is properly defined. Ensure that there are no mistakes in the ID or class name, and the correct symbols are used.

Solve: Check for null

To fix the “cannot read property ‘addEventListener’ of null” error, check that the element is not null before calling the addEventListener() method on it.

We can do this with an if statement:

const btn = document.getElementById('does-not-exist');

console.log(btn); // null

// ✅ Check if element exists before calling addEventListener()
if (btn) {
  // Not called
  btn.addEventListener('click', () => {
    alert('You clicked the button');
  });
}

When a value is placed in between the brackets of an if statement, it is coerced to a Boolean before being evaluated, i.e., truthy values become true, and falsy values become false. null is a falsy value, so it is coerced to false and the code in the if statement block is never run.

Note: In JavaScript, there are six falsy values: undefined, null, NaN, 0, '' (empty string) and false. Every other value is truthy.

We can also use the optional chaining operator (?.) to check if the element is null.

const btn = document.getElementById('does-not-exist');

console.log(btn); // null

// ✅ Check if element exists before calling addEventListener()

// Not called
btn?.addEventListener('click', () => {
  alert('You clicked the button');
});

The optional chaining operator (?.) is null-safe way of accessing a property or calling a method of an object. If the object is nullish (null or undefined), the operator prevents the member access and returns undefined instead of throwing an error.

Cause 2: Inserting the script tag above the DOM element

Another common cause of this error is placing the <script> tag referencing the JavaScript file at a point above where the target element is declared.

For example, in this HTML markup:

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Coding Beauty Tutorial</title>
    <!-- ❌ Script is run before button is declared -->
    <script src="index.js"></script>
  </head>
  <body>
    <button id="btn">Sign up</button>
  </body>
</html>

the script tag is placed in the head tag, above where the button element is declared, so the index.js file will not be able to access the button element.

index.js

const btn = document.getElementById('btn');

console.log(btn); // null

// ❌ TypeError: Cannot read properties of null
btn.addEventListener('click', () => {
  alert('You clicked the button');
});

Solve: Move script tag to bottom of body

To fix the error in this case, move the script tag to the bottom of the body, after all the HTML elements have been declared.

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Coding Beauty Tutorial</title>
  </head>
  <body>
    <button id="btn">Sign up</button>

    <!-- ✅ Script is run after button is declared -->
    <script src="index.js"></script>
  </body>
</html>

Now the index.js script file will have access to the button element and all the other HTML elements, because they would have already been declared when the script is run.

index.js

const btn = document.getElementById('btn');

console.log(btn); // HTMLButtonElement object

// ✅ Works as expected
btn.addEventListener('click', () => {
  alert('You clicked the button');
});

Solve: Access element in DOMContentLoaded event listener

Another way to fix the “cannot read property ‘addEventListener’ of null” error in JavaScript is to add a DOMContentLoaded event listener to the document, and access the element in this listener. With this approach it won’t matter where we place the script in the HTML.

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Coding Beauty Tutorial</title>

    <!-- Script placed above element accessed -->
    <script src="index.js"></script>
  </head>
  <body>
    <button id="btn">Sign up</button>
  </body>
</html>

The DOMContentLoaded event is fired when the browser has fully loaded the HTML, and the DOM tree has been built, but external resources like images and stylesheets may not have loaded. So regardless of where we place the script, the code in the listener is only called after all the declared HTML elements have been added to the DOM.

index.js

document.addEventListener('DOMContentLoaded', () => {
  const btn = document.getElementById('btn');

  console.log(btn); // HTMLButtonElement object

  // ✅ Works as expected
  btn.addEventListener('click', () => {
    alert('You clicked the button');
  });
});

Conclusion

We can fix the “cannot read property addEventListener’ of null” error in JavaScript by ensuring that the correct selector is defined, adding a null check to the element before calling addEventListener(), moving the script tag to the bottom of the body, or accessing the element in a DOMContentLoaded event listener added to the document.

11 Amazing New JavaScript Features in ES13

This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.

11 Amazing New JavaScript Features in ES13

Sign up and receive a free copy immediately.

Ayibatari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.

I’ve a collection of quotes along with names. I’m using update button to update the last quote associated with a specific name but on clicking update button it’s not updating. I’m including code below for server.js file and external js file (main.js).

main.js (external js)

var update = document.getElementById('update');
if (update){
update.addEventListener('click', function () {

  fetch('quotes', {
  method: 'put',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({
    'name': 'Muskan',
    'quote': 'I find your lack of faith disturbing.'
  })
})var update = document.getElementById('update');
if (update){
update.addEventListener('click', function () {

  fetch('quotes', {
  method: 'put',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({
    'name': 'Muskan',
    'quote': 'I find your lack of faith disturbing.'
  })
})
.then(res =>{
    if(res.ok) return res.json()
})
.then(data =>{
    console.log(data);
    window.location.reload(true);
})
})
}

server.js file

app.put('/quotes', (req, res) => {
  db.collection('quotations').findOneAndUpdate({name: 'Vikas'},{
    $set:{
        name: req.body.name,
        quote: req.body.quote
    }
  },{
    sort: {_id: -1},
    upsert: true
  },(err, result) =>{
    if (err) return res.send(err);
    res.send(result);
  })

})

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


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

    более трёх лет назад

  • 2285 просмотров

Потому что 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 );
});


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

04 июн. 2023, в 01:35

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

04 июн. 2023, в 01:25

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

03 июн. 2023, в 23:42

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

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

JavaScript is a client-side scripting language that adds interactivity to our websites/web apps. JavaScript allows us to create and update our web apps’ contents dynamically. If you are a JavaScript developer then I am pretty sure that you might regularly use the addEventListener() method of JavaScript in your projects. In this article, we will be discussing in detail why the “Cannot read property ‘addEventListener’ of null” is encountered and different ways to fix it.

What is addEventListener() in JavaScript?

As discussed above JavaScript is used to add interactivity to web pages and interactivity basically revolves around the events happening on a web page. Events in simple language can be understood as the interactivity of the user with the web pages. The various types of events in JavaScript are onclick, onchange, onmouseover, onmouseout, etc.

addEventListener() is a JavaScript inbuilt function that takes three arguments. First is the event that is to be monitored, the second is the function that needs to be executed when the event is triggered and third is the useCapture. Out of these three arguments, only the first two parameters (i.e event & function) are mostly used.

Syntax:

targetedElement.addEventListener(event, function);

Code language: PHP (php)

Why Does This Error Occur?

The main reason why this error occurs in JavaScript is that you are trying to access the method addEventListner() on such an element that is either not present or cannot be found in the Document Object Model (DOM).

The two reasons for this are:

  • Calling the addEventListener() method on an element that is either not present or could not be found because of some typo or using an incorrect method in your Document Object Model.
  • Using the script tag declaration containing the JavaScript code before the declaration of the DOM element on which you are calling the addEventListener() method.

How to Fix This Error?

Now that we know why this error occurs let us see how to fix/handle this error for both cases.

Case 1: Calling addEventListener() on an element not present in DOM

When we try to call the method addEventListener() on an element that is not present in the Document Object Model (DOM) then this method returns null thus resulting in the above-mentioned error.

Are you using the correct selectors?

The foremost step to fix this error could be to check whether you selected the desired element correctly or not. To ensure this you can make sure that you are using the right selector with the right symbol to target the element like using the ‘#‘ symbol with selectors like getElementByID() or using the ‘.‘ symbol with selectors like getElementByClassName(). Also, make sure that you select the right class/id name with the correct spelling.

Checking for null

Make sure that the element that you are targeting through the addEventListener() method is not null. You can also check this condition using the if statement in JavaScript.

Let us consider a code example in which we will target an anchor tag that is not present.

Code Demonstration:

const myLink = document.querySelector("#no_link"); // there is no anchor tag in our HTML file with id "no_link" if (myLink) { myLink.addEventListener('click', () => { console.log('You visited the link'); }); }

Code language: JavaScript (javascript)

In the above code example, we targeted an anchor tag that was not present in the DOM. Here we used a if condition to check whether the targeted element (anchor tag) exists or not before using the addEventListener() method. As the ancchor tag is not present therefore we’ll get null. Since null is a false value therefore the if block didn’t get executed.

We could have also used the optional chaining operator represented as ”?.” in JavaScript.

Code Demonstration:

const myLink = document.querySelector("#no_link"); // there is no anchor tag in our HTML file with id "no_link" myLink?.addEventListener('click', () => { console.log('You visited the link') });

Code language: JavaScript (javascript)

This operator returns undefined if the value of the object is either null or undefined.

Case 2: Position of Script Tag

This error could also occur due to the wrong placement of the script tag containing the JavaScript code.

Placing

The script tag should always be placed just before the closing body tag. Developers usually make the mistake of placing the script tag inside the head section due to which the JavaScript file gets loaded first and then the content inside the <body> tag of the HTML file gets loaded as the HTML is loaded from top to bottom. Since in this case, the JavaScript file is loaded first, therefore, JavaScript file won’t be able to find any HTML element.

Code Demonstration:

<!DOCTYPE html> <html lang="en"> <head> <title>Codedamn</title> </head> <body> <a id="primary_link" href="#">Visit Link</a> <script src="./app.js"></script> </body> </html>

Code language: HTML, XML (xml)

Now since the JavaScript file is placed just before the closing body tag, it will now have the access to all the HTML elements.

Accessing the element in DOMContentLoaded event listener

This error can also be fixed by using DOMContentLoaded inside the addEventListener() method. Now after wrapping all your JavaScript code inside your addEventListener() having DOMContentLoaded you can access the element that you want to target from this addEventListener() block. Now with this method, you can place your script tag anywhere in your HTML file because the DOMContentLoaded is triggered only once the complete HTML is loaded and the DOM also has been made so it doesn’t matter where we have placed the script tag.

Code Demonstration:

HTML file

<!DOCTYPE html> <html lang="en"> <head> <title>Codedamn</title> <script src="./app.js"></script> </head> <body> <a id="primary_link" href="#">Visit Link</a> </body> </html>

Code language: HTML, XML (xml)

JavaScript file

document.addEventListener("DOMContentLoaded", () => { // your javascript code here const myLink = document.querySelector("#primary_link"); myLink.addEventListener("click", () => { console.log("You visited the link"); }); });

Code language: JavaScript (javascript)

Now, on clicking the button we will get the message “You visited the link” in our console.

Conclusion

In this article, we covered what is addEventListener() in JavaScript in brief and what causes the “cannot read property addEventListener’ of null” error in JavaScript. We also covered various ways to fix this error in JavaScript.

Hope you found this article useful.

Become The Best JavaScript Developer 🚀

Codedamn is the best place to become a proficient developer. Get access to hunderes of practice JavaScript courses, labs, and become employable full-stack JavaScript web developer.

Free money-back guarantee

Unlimited access to all platform courses

100’s of practice projects included

ChatGPT Based Instant AI Help (Jarvis)

Structured Full-Stack Web Developer Roadmap To Get A Job

Exclusive community for events, workshops

Start Learning

Like this post? Please share to your friends:
  • Jquery validate вывод ошибок
  • Jquery getjson ошибка
  • Jquery ajax получить код ошибки
  • Jquery ajax вывести ошибку
  • Jquery ajax post обработка ошибок