Last updated: Feb 29, 2024
Reading time·2 min

To add a click event listener to a button in TypeScript:
addEventListener() method to add a click event listener to it.Here is the HTML for the examples.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> </head> <body> <button id="btn">Click</button> <script src="./src/index.ts"></script> </body> </html>
And here is the related TypeScript code.
const button = document.getElementById('btn'); button?.addEventListener('click', function handleClick(event) { console.log('button clicked'); console.log(event); console.log(event.target); });

We used the document.getElementById method to select the button element.
The getElementById method returns null if no element with the provided id
was found in the DOM, so we had to use the
optional chaining (?.) operator to
short-circuit if the button variable stores a null value.
We called the addEventListener method on the button element.
The addEventListener method takes 2 arguments:
The type of the event to listen for. If you need a list of all of the
available event types, check out this
MDN events list.
A function to be invoked every time the event is triggered.
The event parameter is an object containing many different properties. For
example, event.target refers to the button that was clicked.
You can use the same approach to add a click event listener to multiple buttons.
const buttons = Array.from(document.getElementsByClassName('btn')); buttons.forEach(btn => { btn.addEventListener('click', function handleClick(event) { console.log('button clicked'); console.log(event); console.log(event.target); }); });

We used the document.getElementsByClassName method to select a collection of
elements with the btn class and converted the collection to an array.
The function we passed to the forEach() method gets called for each element
(button) in the array and adds a click event listener to each.
I've also written an article on how to disable a button in TS.