GiH
GiH

Reputation: 14624

Why does a regular for loop not seem to work in jQuery?

I have some code here, can anyone tell me why the for loop doesn't work the way I expect it to?

$(function(){
    var details = $("<li> New list item</li>")
    for( i=0; i<3;i++){
        $('#list').append(details);
        console.log(i);     
    };
});

I'm expecting this to add 3 new list items. But it adds one and then nothing... The console.log does output 3 times though, so why doesn't the append happen 3 times?

The code is not useful, I'm just learning jQuery and wanted to understand why this doesn't work.

Upvotes: 1

Views: 68

Answers (2)

Thomas C. G. de Vilhena
Thomas C. G. de Vilhena

Reputation: 14565

When a DOM element is appended to another it is actually removed from its original location and inserted in the new location. For instance, suppose you have this HTML code:

<div id="p1">
    <div id="c1">Child</div>
</div>
<div id="p2">
</div>

And you execute the following JavaScript code:

$('#p2').append($('#c1'));

Then, the resulting HTML will be:

<div id="p1">
</div>
<div id="p2">
    <div id="c1">Child</div>
</div>

That's why your loop isn't adding any new items to your list after the first iteration, because it is relocating a DOM element to the same location it already is! To insert new items to your list you need to do as Sam suggests, and clone the original item before appending it to the list:

$('#list').append(details.clone());

Upvotes: 2

Sam
Sam

Reputation: 2970

Just clone

$(function(){
var details = $("<li> New list item</li>");
for( i=0; i<3;i++){
    $('#list').append(details.clone());
    console.log(i);     
 };
});

Upvotes: 0

Related Questions