-2

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.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • 2
    `.querySelector()` returns at most one element reference. If you want to add the event listener to all elements, you have to use `.querySelectorAll()` and then loop through the list of elements and add it to each one. – Pointy Aug 30 '23 at 14:04

1 Answers1

1

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.

vlanto
  • 457
  • 6