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

127
Visualizações
Assigning same function to multiple values

The #Button1 works when I click it but #Button2 does not. If I change the order of them then 2 works but 1 doesn't. Can you not set the same function to multiple events? How would I make this work. Both buttons are on different html pages if that makes a difference.

document.addEventListener('DOMContentLoaded', function() {
    document.querySelector('#Button1').onclick = fun;
    document.querySelector('#Button2').onclick = fun;
});

function fun() {
    alert();
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You are trying to attach an event to something that does not exist. So of course it will throw an error. Looking at the developer console you would see an error message. VM1455:1 Uncaught TypeError: Cannot set properties of null (setting 'onclick')

If only one element exist you can make one selector that targets both

document.querySelector('#Button1, #Button2').addEventListener("click", fun);

or use a common class on the buttons

document.querySelector('.myFunButton').addEventListener("click", fun);

Or you can check to see if the element exists.

document.querySelector('#Button1')?.addEventListener('click', fun);
document.querySelector('#Button2')?.addEventListener('click', fun);
about 4 years ago · Juan Pablo Isaza Relatório

0

Try:

document.addEventListener('DOMContentLoaded', function() {
    if(document.querySelector('#Button1'))
        document.querySelector('#Button1').onclick = fun;
    if(document.querySelector('#Button2'))
        document.querySelector('#Button2').onclick = fun;
});
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