tags:

views:

39

answers:

4

I have:

<div id="list">
</div>

and then:

$('#list').append('a<br>');
$('#list').append('b<br>');
$('#list').append('c<br>');

But what I would like is:

<ul id="list">
</ul>

Q: How can I append to an unordered list in jQuery using the DOM and not using .html?

+2  A: 

Use appendTo(): http://api.jquery.com/appendTo/

var list = $('#list');

$('<li></li>').appendTo(list).text('List item 1');

You can then use chaining to define additional properties such as text and attributes.

Yi Jiang
+1  A: 
var list = $('<ul id="list"/>');
list.append('<li>content</li>');
Ionut Staicu
The variable just make things slower and is not necessary if it's not gonna be re-used somewhere else in the script.
Fred Bergman
Indeed, but from his example, he wants to add more than one element. So this solution is kinda faster than appending elements to existing elements.
Ionut Staicu
+1  A: 

You probably want to do:

$('#list').append('<li>Item #1</li><li>Item #2</li>');
Fred Bergman
+1  A: 

The .append() method is still correct. The question is what are you appending?

Since #list is a <ul>, you need to .append() <li> elements.

Of course, if the #list is empty, and you're appending several at once, you could always use .html() or .innerHTML instead.

$('#list').html("<li>a</li><li>b</li><li>c</li>");

or

document.getElementById('list').innerHTML = "<li>a</li><li>b</li><li>c</li>";

...which would be fastest.

Then use .append() thereafter for additional elements.

patrick dw