Use event delegation (usually better)
Attach a single listener to a parent element that already exists:
document.body.addEventListener('click', (event) => {
if (event.target.matches('.btn')) {
handleClick(event);
}
});
Now any current or future .btn element will work automatically.
Use event delegation (usually better)
Attach a single listener to a parent element that already exists:
Now any current or future .btn element will work automatically.