Nick Nick - 11 months ago 52
jQuery Question

jQuery .appendTo or more general for loop not working as expected

jQuery newbie here. I'm working through R Murphy's jQuery Fundamentals and am on the Manipulation exercises in the jQuery Basics section.

The first question in that section asks you to add five new list items to the end of the unordered list #myList.

My approach was to do the following:

var $newItem = $('<li>New Item</li>');
var $ul = $('#myList');

for (var i=0;i<5;i++){

However this doesn't work as it only inserts one list item into the list, not 5.

The solution provided by the author is very close to mine, the only difference being she doesn't store the new list item in a variable, but rather uses a literal:

var $ul = $('#myList');
for (i=0; i<5; i++) {
$('<li>List item ' + i + '</li>').appendTo($ul);

It seems like my approach should work also so I'm struggling to understand why it doesn't.


Thanks in advance,


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++){

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