1

Hello I have this piece of code in TypeScript

 var btn  = document.getElementsByClassName("btn-up") as EventTarget;
 btn.addEventListener('click', (event) => {
 console.log('clickcc');
})

And It throws me this error * Type 'HTMLCollectionOf' is missing the following properties from type 'EventTarget': addEventListener, dispatchEvent, removeEventListener *

Please how to fix it?

jhrmdk
  • 603
  • 7
  • 13
  • I fixed it with document.getElementById selector, but if I want to bind more buttons, how to do it? – jhrmdk Jun 09 '20 at 10:53
  • 1
    Does this answer your question? [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – James Jun 09 '20 at 12:19

1 Answers1

3

This will returns the array of elements, not just a single element :

document.getElementsByClassName("btn-up") as EventTarget

To :

document.getElementsByClassName("btn-up")[0] as EventTarget

WORKING DEMO :

Edit #SO-TS-EventTarget

Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122