Search code examples
javascripthtmlcsscreateelement

Style all Elements of a div created via .createElement('div')


So I'm creating multiple new child divs inside another parent div with this code:

var parentDiv = document.querySelector('.parent-div')
const newDiv = document.createElement('div');
parentDiv.appendChild(newDiv);

So now I want to add an onlick event for every div I created, that resets the color for every other div inside the parent div, so that no multiple child divs are selected, and then set the color only for the clicked div to another color!

Any ideas?


Solution

  • var parentDiv = document.querySelector('.parent-div');
    for (let i = 0; i < 10; ++i) {
      const newDiv = document.createElement('div');
      newDiv.className = "my-class";
      newDiv.innerText = `Foo${i}`;
      parentDiv.appendChild(newDiv);
    }
    parentDiv.onclick = (event) => {
      document.querySelectorAll('.my-class').forEach((el) => {
        el.className = "my-class";
      });
      event.target.className += " active";
    }
    .my-class {
      color: red;
    }
    
    .active {
      color: blue;
    }
    <div class="parent-div"></div>