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

Time:10-17

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?

CodePudding user response:

        let parentDiv = document.querySelector('.parent-div');
        for (let x = 0; x < 10; x  ) {

         let newDiv = document.createElement('div');
       newDiv.classList.add('see')

        parentDiv.appendChild(newDiv);
      }


      parentDiv.addEventListener('click', (e) => {
       if (e.target.tagName === 'DIV') {
         e.target.style.backgroundColor = 'red';
       }
     })

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The approach proposed here is aware of which div was clicked the last time, changes its style accordingly and creates the onclick when the item is created.

var parentDiv = document.querySelector('.parent-div');
let lastDiv = undefined;
for (let i = 0; i < 10; i  ) {
    let newDiv = document.createElement('div');
    newDiv.style.width = "100px";
    newDiv.style.height = "100px";
    newDiv.style.backgroundColor = "black";
    newDiv.style.border = "1px solid white";
    newDiv.onclick = function() {
        if (lastDiv) lastDiv.style.backgroundColor = "black";
        newDiv.style.backgroundColor = "green";
        lastDiv = newDiv;
    };
    parentDiv.appendChild(newDiv);
}
<div class="parent-div"></div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

I'm not sure if this is how you would want to do it for many reasons, but it might be beneficial for you to change the HTML value of the parent div. For example,

var parentDiv = document.querySelector('.parent-div')
parentDiv.innerHTML = parentDiv.innerHTML   "<div class='{class name}'></div>";
  • Related