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

159
Views
No se puede usar addEventListener con for in loop

Estoy tratando de usar el bucle for...in para agregar el detector de eventos al botón porque no quiero repetirme en caso de que haya muchos botones/elementos. Pero me da error de key.addEventListener is not a function . ¿Qué estoy haciendo mal aquí?

 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 answers
Answer question

0

key es la clave de cadena del objeto, no el elemento DOM en la variable con el mismo nombre.

Ponga los elementos DOM en el objeto también.

 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 Report

0

  • document.querySelectorAll('button'); esta declaración selecciona todos los botones de DOM.
  • buttons.forEach foreach recorre todos los botones y agrega un evento de clic, es más fácil y legible.

 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 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!