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

150
Vistas
Cannot use addEventListener with for in loop

I'm trying to use the for...in loop to add the event listener to the button because I don't want to repeat myself in case there are many buttons/elements. But it gives me an error of key.addEventListener is not a function. What am I doing wrong here?

const firstBtn = document.querySelector('.first-btn');
const secondBtn = document.querySelector('.second-btn');
const data = { firstBtn:'apple', secondBtn:'orange' };

for(const key in data) {
  key.addEventListener('click', function() {
    console.log(data[key]);
  });
}
<button class="first-btn">First</button>
<button class="second-btn">Second</button>

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

key is the string key of the object, not the DOM element in the variable with the same name.

Put the DOM elements in the object as well.

const firstBtn = document.querySelector('.first-btn');
const secondBtn = document.querySelector('.second-btn');
const data = [{
    el: firstBtn,
    msg: 'apple'
  },
  {
    el: secondBtn,
    msg: 'orange'
  }
];

for (const obj of data) {
  obj.el.addEventListener('click', function() {
    console.log(obj.msg);
  });
}
<button class="first-btn">First</button>
<button class="second-btn">Second</button>

about 4 years ago · Juan Pablo Isaza Denunciar

0

  • document.querySelectorAll('button'); this statment selects all buttons from DOM.
  • buttons.forEach foreach loop through all the buttons and add click event it's easier and readable.

const buttons = document.querySelectorAll('button');
buttons.forEach(btn => {
  btn.addEventListener('click', function() {
    console.log(btn);
  });
})
<button class="first-btn">First</button>
<button class="second-btn">Second</button>

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