Home > Software design >  addEventListener function not working in javascript
addEventListener function not working in javascript

Time:04-22

I am trying to check if a function that is meant to be triggered by a click with a console.log but the console message never comes up

<script src="e-com.js" async></script>

this is how i linked the js file in the head

<a href="" id="remove">Remove</a>

this is the link I want the event on

let removeItem=document.getElementById("remove")
for (i=0; i<removeItem.length; i  ){
let  remove = removeItem.addEventListener("click", function(){

  console.log("Clicked");
  })
}

This is the js function

CodePudding user response:

.getElementById() doesn't return an array since you're not allowed to have more than one element with a single id.

Therefore, the for loop failed.

Try

let removeItem=document.getElementById("remove")

removeItem.addEventListener("click", function(){

  console.log("Clicked");
})

CodePudding user response:

The issue seems to be that you are trying to loop over the result of getElementById(), which doesn't return an iterable.


To fix it, you just need to remove the loop. The code below should work correctly^.

const removeItem = document.getElementById("remove");

removeItem.addEventListener("click", () => {
  console.log("Clicked!");
});
<a href="" id="remove">Remove</a>

According to MDN Web Docs:

The Document method getElementById() returns an Element object representing the element whose id property matches the specified string.

As it states, getElementById() returns an Element, which is just an object, in short. This is why you cannot iterate over it.


If you wanted to listen to multiple objects with a for loop, you need to change a few things.

First, you can't use an id, as the id attribute is unique, and can only be used once in a HTML document. Therefore, to get multiple elements, you need to use the class attribute. See an example of the class attribute in use below.

<div >Division!</div>

The class attribute can be used by any HTML element.

So, to get all of the classes and iterate over them, you need to use either the getElementsByClassName() method, or the querySelectorAll() method.

The only difference between the two is that getElementsByClassName() returns a live HTMLCollection, while querySelectorAll() returns a static HTMLCollection.

If you were to use querySelectorAll(), your code would look like this^.

const removeItem = document.querySelectorAll("remove");

Array.from(removeItem).forEach((ele) => {
  ele.addEventListener("click", () => {
    console.log("Clicked!");
  });
});
<a href="" >Remove</a>
<a href="" >Remove</a>
<a href="" >Remove</a>


Both of these solutions should work correctly, but they depend on what you need to accomplish.


^ The code has been modified slightly.

  • Related