jquery loop not working properly

this is my loop. I want to print 7 li tag and 5 ul tags. This is my code.

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

        for (var j = 0; j <= 6; j++) {

            $("#calendar ul").append("<li></li>").addClass("days");
            $("#calendar ul li").addClass("day");

            count = count + 1;

but the result is quite different from the expectation. There are 35, 28, 21, 14 and 7 li tags in each consecutive loop. I understand why it is so. The li tags are appended to all the ul's in the #calendar div.

Now, what is the proper way to appended li to the ul tags without the repeatation? Thanks.

Answers 1

  • The error is here its appending li to all the class items every and each time he goes in second loop(starting from first ul) to prevent that block it with id (i left the class name assuming it is important to handle css or something).

    here is the simple solution

    for (var i = 1; i <= 5 ; i++) {
                $("#calendar").append("<ul class='days' id='"+i+"'></ul>")
            for (var j = 1; j <= 7; j++) {
                $("#calendar #"+i+".days ").append("<li class='day'></li>");


Related Articles