Phillip Senn
Phillip Senn

Reputation: 47595

Equivalent to .append for a list element

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?

Upvotes: 2

Views: 543

Answers (4)

user113716
user113716

Reputation: 322452

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.

Upvotes: 1

Fred Bergman
Fred Bergman

Reputation: 2020

You probably want to do:

$('#list').append('<li>Item #1</li><li>Item #2</li>');

Upvotes: 1

Ionuț Staicu
Ionuț Staicu

Reputation: 22156

var list = $('<ul id="list"/>');
list.append('<li>content</li>');

Upvotes: 1

Yi Jiang
Yi Jiang

Reputation: 50095

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.

Upvotes: 3

Related Questions