how can i assign an event listener to all created elements in a closed loop

Simply use event delegation : any click on div belong to his parent section.preview, then check if the clicked element corresponds to your div (event.target)
sample code:

const preview = document.querySelector('.preview')
  ,   rColor  =()=>Math.floor(Math.random() *255) +1
  ;
for (i=100;i--;)
  {
  let div = document.createElement('div');
  div.style.backgroundColor = `rgb(${rColor()},${rColor()},${rColor()})` 
  preview.appendChild(div);
  }
preview.onclick=e=>  // get click event on any elements of section.preview  
  {
  if (!e.target.matches('div')) return  // reject other elements click
  e.target.style.backgroundColor = `rgb(${rColor()},${rColor()},${rColor()})` 
  }
body, html {
  width          : 100vw;
  height         : 100vh;
  display        : flex;
  justify-content: center;
  align-items    : center;
  margin         : 0;
  padding        : 0;
  }
* {
  box-sizing     : border-box;
  }
.preview {
  width          : 100vw;
  height         : 100vh;
  display        : flex; 
  justify-content: center; 
  align-items    : center; 
  flex-wrap      : wrap;
  }
.preview > div {
  height : 10vh; 
  width  : 10vw;
  }
<section class="preview"></section>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top