Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

211
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda