Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

141
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório

0

Just to suggest a more robust and flexible way:

// Utility functions
const EL = (sel, EL) => (EL||document).querySelector(sel);
const ELS = (sel, EL) => (EL||document).querySelectorAll(sel);
const ELNew = (tag, prop) => Object.assign(document.createElement(tag), prop);

// Now...

// Get element (Use an ID, not a class)
const EL_parent = EL('#parent');

// Function to toggle "is-active" class
const toggleActive = (EL_target, EL_parent) => {
  const EL_active = EL(".is-active", EL_parent);
  if (EL_active) EL_active.classList.remove("is-active");
  EL_target.classList.add("is-active");
};

// Function to create new child elements
const newChild = (content) => ELNew("div", {
  className: "child",
  innerHTML: content,
  onclick() {
    toggleActive(this, EL_parent);
  }  
});

// Create a couple of elements....
EL_parent.append(
  newChild("1 Lorem"),
  newChild("2 Ipsum"),
  newChild("3 Dolor"),
);
.is-active {
  background: gold;
}
<div id="parent"></div>

So just a better way, and to avoid sloppy code like className = or Event.target without the use of .closest(), as shown in the other answers.

about 4 years ago · Juan Pablo Isaza Relatório

0

        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';
       }
     })
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda