Why do multiple `.appendTo` calls on a newly created jQuery element only append it once?

Your approach creates a single li element outside of the loop and tries to append the same thing to the ul five times. But since you hold a reference to a single li, each time you append it, it actually removes it from where it is and re-adds it there..

In the solution the li is created inside the loop so it is a new li element each iteration.

You could change your own to use the .clone() docs method

for (var i=0;i<5;i++){
    $newItem.clone().appendTo($ul);
};

This way it will create a copy and you then add that to the ul.

Leave a Comment