1

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>')
    })
})
8
  • 3
    Why would you want to do this? Commented Sep 25, 2013 at 11:03
  • 3
    Whats wrong with a for loop? Commented Sep 25, 2013 at 11:04
  • 1
    <li> can't be the child of <body>. You need either <ul> or <ol>. Commented Sep 25, 2013 at 11:05
  • you can use array to define lgt Commented Sep 25, 2013 at 11:05
  • This is not what $.each has been designed for. $.each is working on "collections", i.e. lists of objects like jQuery objects, arrays etc. A number is not a list of objects ... Commented Sep 25, 2013 at 11:05

3 Answers 3

4

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..

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

2 Comments

that's a comment on why it doesn't work but not a solution to the problem as such
The solution should be easy to get from here, or the questioner could ask for more advice if it is not clear. But I will add the solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.