Jitender
Jitender

Reputation: 7971

$.each instead of for loop in jquery

I want to append li five times in body using each function. But it is not working. It should append five li in body Note: It is just a sample code

$(function(){
    var lgt= 5;
    $.each(lgt,function(i){ 
        $('body').append('<li>'+i+'</li>')
    })
})

Upvotes: 1

Views: 581

Answers (3)

Raidri
Raidri

Reputation: 17550

$.each expects an array as first parameter, not a number.
You could use var lgt = new Array(5) instead of var lgt = 5.

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

The first question is Why not use a for loop ?

If you still need to go this way you can use

$(function(){
    var lgt= 5;
    $.each(new Array(lgt),function(i){ 
        $('body').append('<li>'+i+'</li>')
    });
});

but as others have mentioned you cannot add li elements directly to the body..

Upvotes: 4

Gaz Winter
Gaz Winter

Reputation: 2989

Check out the jQuery $.each documentation

I dont think what you are trying to do is valid.

It needs a collection to loop through, you are just passing it a single integer

Upvotes: 0

Related Questions