Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

71
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!