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>
3
  • 4
    You are appending the same li over and over and over rather than creating a new one. Commented Aug 29, 2012 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. Commented Aug 29, 2012 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: stackoverflow.com/questions/327047/… Commented Aug 29, 2012 at 14:28

6 Answers 6

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.

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

Comments

1

Use clone.

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

Comments

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)

Comments

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.

Comments

0

You could use a while loop:

var i = 1;

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

Comments

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

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

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

Comments

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.