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

72
Visualizações
Dynamically created divs with added class don't have styling

I'm trying to generate some divs dynamically through a for loop. They don't have the color and size styling, even though I've added a class and I can see the class in the developer tools.

public addDivs() {
   for(let i = 0; i < 10; i++) {
      let div = document.createElement('div');
      div.classList.add('test');
      div.innerHTML = 'testing'
   }
}


.test {
   color:red;
   background-color:green;
   height: 40px;
   width: 40px;
}

When I add styling like this it does work.

public addDivs() {
   for(let i = 0; i < 10; i++) {
      let div = document.createElement('div');
      div.innerHTML = 'testing'
      div.style.color = 'red';
   }
}

Is it possible (without JQuery) to get the styling from a css file?

edit: Also I should add that it started to fail only when I put the code in a for loop.

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

0

Append the element after creating it. Existing classes and styles works with dynamically created nodes.

function addDivs() {
   for(let i = 0; i < 10; i++) {
      let div = document.createElement('div');
      div.classList.add('test');
      div.innerHTML = 'testing:'+i;
      document.querySelector("body").appendChild(div);
   }
}
addDivs();
.test {
   color:red;
   background-color:green;
   height: 40px;
   width: 100px;
   margin-bottom:4px;
}

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