Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

121
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda