Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I assemble a <ul> using jQuery append()?

Tags:

jquery

I'm trying to use the append function and encountered this:

$("#details").append('<ul>'); for (var i = 0; i < 10; i++) {     $("#details").append('<li>something</li>'); } $("#details").append('</ul>'); 

It appears that the <li> elements renders OUTSIDE the <ul> tag.

Is this a jQuery bug?

like image 208
Brian Liang Avatar asked Jul 14 '09 15:07

Brian Liang


People also ask

How do you append something in jQuery?

jQuery append() MethodThe append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.

How can add Li in UL dynamically using jQuery?

Answer: Use the jQuery append() Method You can simply use the jQuery append() method to add <li> elements in an existing <ul> element. The following example will add a <li> element at the end of an <ul> on click of the button.

How do I add something to an unordered list?

You create an unordered list using the ul tag. Then, you use the li tag to list each and every one of the items you want your list to include. tag. This means that the li tag is the child of the ul tag.


2 Answers

Nope, you can't use it like that. append is an atomic operation, which creates the element directly.

// The <ul> element is added to #details, then it is selected and the jQuery // selection is put in the "list" variable. var list = $('<ul/>').appendTo('#details'); for (var i = 0; i < 10; i++) {     // New <li> elements are created here and added to the <ul> element.     list.append('<li>something</li>'); } 

Alternatively, generate the HTML and add it all at once (this will be more similar to your original code):

var html = '<ul>'; for (var i = 0; i < 10; i++) {     html += '<li>something</li>'; } html += '</ul>'; $('#details').append(html); 

This code is noticeably faster when dealing with many elements.

If you need a reference to the list, just do the following instead of $('#details').append(html);:

var list = $(html).appendTo('#details'); 
like image 87
Blixt Avatar answered Sep 19 '22 18:09

Blixt


No, it's a programmer bug. <li>s are attached to their <ul> or <ol>, not to its container. And appending a close tag is nonsensical.

You're basically working as if what you were appending were raw HTML, and it's not; you're actually working with the DOM.

Try this:

var list = $("#details").append('<ul></ul>').find('ul'); for (var i = 0; i < 10; i++)     list.append('<li>something</li>'); 

Note: please see (and upvote) Blixt's answer, which expands on a couple different options that are superior for various purposes. It deserves attention and hasn't been getting it.

like image 37
chaos Avatar answered Sep 22 '22 18:09

chaos