2

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>
js999
  • 2,063
  • 4
  • 26
  • 34
  • 4
    You are appending the same li over and over and over rather than creating a new one. – Kevin B Aug 29 '12 at 14:17
  • Why would it? You don't do anything with the HTML you're generating even if you weren't appending the same list item. Also, when asking, it's best to describe the behavior you *are* seeing, to make the question even easier to answer. – Dave Newton Aug 29 '12 at 14:19
  • There are a lot of different answers posted here. Some of which suggest different methods of creating the new elements. Here is a long discussion on what to do, and why: http://stackoverflow.com/questions/327047/what-is-the-most-efficient-way-to-create-html-elements-using-jquery – Per Salbark Aug 29 '12 at 14:28

6 Answers6

1

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.

Kevin B
  • 94,570
  • 16
  • 163
  • 180
1

Use clone.

$li.clone().appendTo('ul');
Simon Arnold
  • 15,849
  • 7
  • 67
  • 85
1

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)
Ram
  • 143,282
  • 16
  • 168
  • 197
0

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.

Per Salbark
  • 3,597
  • 1
  • 23
  • 24
0

You could use a while loop:

var i = 1;

while (i <= 3){
    $('ul').append('<li>Text</li>');
    i=i+1;
}
Alex
  • 8,875
  • 2
  • 27
  • 44
0
var $ul = $('<ul />');

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

$('<div>').append($ul);
adeneo
  • 312,895
  • 29
  • 395
  • 388