Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

128
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda