Please tell me why when I click on the ones "1111111111" in the browser, the function is called, and when I click on the twos "2222222222", the function is not called, please explain why and how to fix it?
const contactButton = document.querySelector('.contact-button');
contactButton.addEventListener('click', () => {
console.log('Hello')
})
<div class="contact-button">1111111111</div>
<div class="contact-button">2222222222</div>
I will be grateful for help. Thank you.
>Solution :
The reason the click event is not being triggered for the second "2222222222" element is due to the way you are selecting the .contact-button elements and adding event listeners to them.
Here’s how you can modify your JavaScript code:
const contactButtons = document.querySelectorAll('.contact-button');
contactButtons.forEach(button => {
button.addEventListener('click', () => {
console.log('Hello');
});
});
With this change, the event listener will be added to all elements with the class contact-button, and clicking any of them will log "Hello" to the console.