Reputation: 2083
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
Reputation: 318182
var $ul = $('<ul />');
for (i=0; i<3; i++) {
$ul.append($('<li />', {text : 'text'}));
}
$('<div>').append($ul);
Upvotes: 0
Reputation: 9031
You could use a while loop:
var i = 1;
while (i <= 3){
$('ul').append('<li>Text</li>');
i=i+1;
}
Upvotes: 0
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
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
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