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

120
Views
loop not writing expected output in the dom 15 times

why do the loop not writing expected output in the dom 15 times

I am trying to create an elemnt div 15 times with another div child

here is the code


for(let i=1;i<=15;i++){
    let smalldiv=document.createElement("div").textContent=i;
    let pr =document.createElement("div");
    pr.textContent="product";
};
smalldiv.appendChild(pr);


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

0

let smalldiv=document.createElement("div").textContent=i;

doesn't set smalldiv to the DIV. When you write

let x = y = z;

it's equivalent to

y = z;
let x = y;

so you're setting smalldiv to the textContent that you assigned i to.

And even if you did set smalldiv to the DIV, you never append it to the DOM, so you wouldn't see the results.

Since you're appending pr to smalldiv after the loop, you're just appending the last pr. But that won't work either, because the scope of pr is the loop body, so you can't refer to it after the loop is done. You should append it inside the loop.

Don't use a DIV for numbered items, use an ordered list <ol>, with <li> elements within it.

let ol = document.createElement("ol");
for(let i=1;i<=15;i++){
    let pr =document.createElement("li");
    pr.textContent="product";
    ol.appendChild(pr);
};
document.body.appendChild(ol);

about 4 years ago · Juan Pablo Isaza Report

0

First create the div smalldiv, then add the textContent. Then you need to append the elements to the DOM using an element already in the DOM or append to the document.body.

for(let i=1;i<=15;i++){
    // create the div and assign the variable
    let smalldiv=document.createElement("div");
    // set the textContent once created
    smalldiv.textContent = `${i}. `;
    // create new div 'pr'
    let pr = document.createElement("span");
    // assign its content
    pr.textContent="product";
    // append pr to smalldiv
    smalldiv.append(pr);
    // append smalldiv to the body
    document.body.append(smalldiv);
};

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!