Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

76
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda