Home > Enterprise >  loop not writing expected output in the dom 15 times
loop not writing expected output in the dom 15 times

Time:09-30

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);


CodePudding user response:

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);

CodePudding user response:

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);
};

  • Related