I have a simple click function in Javascript that I am trying to get to work. The issue I am having is that the click function is only working for the first element with the class, where I would like it to fire when you click any elements with the class.
const element = document.querySelector('.js-element')
if ( element ) element.addEventListener('click', function () {
alert('click');
})
Can anyone please advise where I am going wrong?
Thanks
querySelector. That means you selected a single element and added a listener to that one element. Either usequerySelectorAlland add a listener to each element, or add a listener to the container (or the body) and use event delegationquerySelectorAll(), you can.forEach()on the result.