Home > front end >  Javascript For loop appends same element once [closed]
Javascript For loop appends same element once [closed]

Time:10-07

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

CodePudding user response:

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:

  • Related