Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

203
Views
sound when clicking a button works for one but not for ALL

Can someone show me why if I try to play a sound like so

const button = document.querySelector(".button");

button.addEventListener("click", function () {
  document.getElementById("click").play("click.mp3");
});

the sound will only play on the first button (I understand this since it is targeting the first element) with the class .button but if I use querySlectorAll it does not play at all please?

And how can I make it play in all the buttons with the class .button?

Thanks in advance.

Thanks to Barmar for suggesting to use a loop. I did like in below and it works great.


for (let button of buttons) {
  button.addEventListener("click", function () {
    document.getElementById("click").play("click.mp3");
  });
  console.log(button);
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

In my case efficient solution will be addEventListener to the parent that contain these buttons and make a check condition that if clicked element has some class or data attribute then make your sound play.

about 4 years ago · Juan Pablo Isaza Report

0

The most elegant way would be to use querySelectorAll, which returns a NodeList, which can be coerced into an array.

const buttons = Array.from(document.querySelectorAll(".button"));

buttons.forEach(button => {
    button.addEventListener("click", function () {
        document.getElementById("click").play("click.mp3");
    });
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!