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

224
Views
JavaScript How to create elements into each created element?

I'm trying to put a content div into each parent div, but this way it puts all the content divs to the first parent div, not each parent div. I've tried to do it in 2 for loops, tried forEach, but just can't figure it out.

        for (let i = 0; i < 5; i++) {
           const parent = document.createElement("div");
           parent.classList.add("parent");
           parent.setAttribute("id","parent");
           document.getElementById("container").appendChild(parent);
           const content = document.createElement("div");
           content.classList.add("content");
           document.getElementById("parnet").appendChild(content);
        }

Ty for your answer

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You're using id's to select your parents with. But you can't have multiple elements with the same id value. getElementById will also look for the first occurence of the id, so you will always get the first parent element.

Besides that, you already have a reference to the parent in your parent variable. No need to look it up again, just use the reference you already have.

const container = document.getElementById("container");

for (let i = 0; i < 5; i++) {
  const content = document.createElement("div");
  content.classList.add("content");

  const parent = document.createElement("div");
  parent.classList.add("parent");

  parent.append(content);
  container.append(parent);
}
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!