js999
js999

Reputation: 2083

How to generate an html list by using jquery

Why the following code (1) does not give me the following output (2)

(1)

var $ul = $('<ul>');
var $li = $('<li>').text('text');
$ul.append($li);
$ul.append($li);
$ul.append($li);
$('<div>').append($ul);

(2)

<div>
   <ul>
     <li> text <li>
     <li> text <li>
     <li> text <li>
   </ul>
</div>

Upvotes: 2

Views: 196

Answers (6)

adeneo
adeneo

Reputation: 318182

var $ul = $('<ul />');

for (i=0; i<3; i++) {
    $ul.append($('<li />', {text : 'text'}));
}

$('<div>').append($ul);

Upvotes: 0

Alex
Alex

Reputation: 9031

You could use a while loop:

var i = 1;

while (i <= 3){
    $('ul').append('<li>Text</li>');
    i=i+1;
}

Upvotes: 0

Ram
Ram

Reputation: 144679

You can use clone() method.

var $ul = $('</ul>');
var $li = $('</li>', {text:'text'});
$ul.append($li.clone());
$ul.append($li.clone());
$ul.append($li.clone());
$('<div/>').append($ul)

Upvotes: 1

Simon Arnold
Simon Arnold

Reputation: 16167

Use clone.

$li.clone().appendTo('ul');

Upvotes: 1

Kevin B
Kevin B

Reputation: 95023

You are appending the same li over and over and over rather than creating a new one.

I suggest instead creating an html string and appending it all at once.

var strHTML = "<div><ul>";
strHTML += "<li>text</li>";
strHTML += "<li>text</li>";
strHTML += "<li>text</li>";
strHTML += "</ul></div>";
var elements = $(strHTML);

//OR in jQuery 1.8.0+    
//var elements = $.parseHTML(strHTML);

Also, you should always pass comlete html into $(), meaning $("<li />") instead of $("<li>") otherwise later on when you upgrade jQuery you'll have a lot of work to do.

Upvotes: 1

Per Salbark
Per Salbark

Reputation: 3645

Try

$("<div/>")
    .append(
       $("<ul/>")
          .append(
              $("<li/>")
                  .text(" text ")
          )
          .append(
              $("<li/>")
                  .text(" text ")
          )
          .append(
              $("<li/>")
                  .text(" text ")
          )
    );

When you append the same $li several times you are just movin it around. You need to create a new one for each append.

Upvotes: 0

Related Questions