Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading