“.addEventListener is not a function” why does this error occur?

1.0K    Asked by Ankesh Kumar in Salesforce , Asked on Apr 16, 2021
Trying to loop over all the expandable steps in this example but when I run the code below I get this error:this.template.querySelectorAll(...).addEventListener is not a function import { LightningElement } from 'lwc'; export default class AddProductWizard extends LightningElement { renderedCallback(){ this.template.querySelectorAll('.slds-setup-assistant').addEventListener('click',this.handleClick); } handleClick(e){ console.log("Clicked " + this.id); } }

What is reason behind getting  error “addeventlistener is not a function”. Any help would be appreciated

Answered by Anurag Singhal

The problem is with your code is that 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>

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...

      <code>  var comment = document.getElementsByClassName("button");</code>

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];


Your Answer

Answers (2)

The intuitive design of the Block Blast Solver ensures that players of all ages and experience levels can use it to master the game without any complications.

5 Days

For many bitlife games are a stress reliever. Immersing yourself in a virtual world can help you relax after a long day.

4 Weeks

Interviews

Parent Categories