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

110
Views
Javascript For loop appends same element once

This is to understand the logic of JS Loop. In the following code i expect that the <li> element will append 3 times inside the <ul> tag. So that i should get 3 <li> tag inside the <ul> tag. As per my understanding any actions inside the loop will work based on the condition. As per that I should get 3 blank <li> tag here. But i get only 1. Anyone can explain whats wrong on my approach and how should i need to write it. Thanks in Advance!

let ul = document.querySelector("ul");
let li = document.createElement("li");
for (i = 0; i <=3; i++) {
  ul.appendChild(li);
}
about 4 years ago ยท Juan Pablo Isaza
2 answers
Answer question

0

You need to create a new element each time. If you are appending the same element multiple times, it will move it in the DOM, but not clone it.

One simple solution is use cloneNode:

let node = document.createTextNode("๐Ÿ˜€")
for (i = 0; i <3; i++) 
  document.body.appendChild( node.cloneNode() )

Note:

Cloning a node copies all of its attributes and their values, including intrinsic (inline) listeners. It does not copy event listeners added using

about 4 years ago ยท Juan Pablo Isaza Report

0

why

appendChild replace self element bug

solutions

  1. create new li inside the loop

const ul = document.createElement("ul");
// li = document.createElement("li");

for (i = 0; i < 3; i++) {
   const li = document.createElement("li");
   // console.log('i =', i, ul);
   ul.insertAdjacentElement('beforeend', li);
}
ul;
// <ul>โ€‹โ€‹<li>โ€‹</li>โ€‹<li>โ€‹</li>โ€‹<li>โ€‹</li>โ€‹</ul>โ€‹
      

  1. create all children with DOM string

const ul = document.createElement("ul");
let li = '';

for (i = 0; i < 3; i++) {
   li += '<li></li>';
}

ul.insertAdjacentHTML('beforeend', li);

ul;
// <ul>โ€‹โ€‹<li>โ€‹</li>โ€‹<li>โ€‹</li>โ€‹<li>โ€‹</li>โ€‹</ul>โ€‹
      

ref

https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild

https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement

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!