How to add a list item to an existing unordered list
Asked Answered
R

14

572

I have code that looks like this:

<div id="header">
    <ul class="tabs">
        <li><a href="/user/view"><span class="tab">Profile</span></a></li>
        <li><a href="/user/edit"><span class="tab">Edit</span></a></li>
    </ul>
</div>

I'd like to use jQuery to add the following to the list:

<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>

I tried this:

$("#content ul li:last").append("<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>");

But that adds the new li inside the last li (just before the closing tag), not after it. What's the best way to add this li?

Runofthemill answered 17/7, 2009 at 19:28 Comment(0)
S
853

This would do it:

$("#header ul").append('<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>');

Two things:

  • You can just append the <li> to the <ul> itself.
  • You need to use the opposite type of quotes than what you're using in your HTML. So since you're using double quotes in your attributes, surround the code with single quotes.
Stationary answered 17/7, 2009 at 19:29 Comment(1)
just as a side note, you can use prepend instead of append in case you want to add as the first element instead of the lastHydrochloride
F
528

You can also do it in a more 'object' and still easy-to-read way:

$('#content ul').append(
    $('<li>').append(
        $('<a>').attr('href','/user/messages').append(
            $('<span>').attr('class', 'tab').append("Message center")
)));

You don't have to fight with quotes then, but you must keep trace of braces :)

Fransen answered 9/11, 2011 at 9:33 Comment(5)
Wouldn't your approach start new tags but not close them?Appoggiatura
No, jquery creates tags using DOM manipulation, so it has only to know it's nameFransen
I love this. I hate messing with strings and quotes :) BTW: Other option would be https://mcmap.net/q/10141/-javascript-equivalent-to-printf-string-formatCran
This is by far the more preferable way, that is to use the more object-oriented manner.Tiger
You can escape any special HTML characters in user-input by using $('<span>').text(unsafe_user_input) instead of the direct append("Message center").Central
B
57

If you are simply adding text in that li, you can use:

 $("#ul").append($("<li>").text("Some Text."));
Bannockburn answered 7/3, 2014 at 0:42 Comment(1)
Works like a charm for me after trying all failed solution..Abortive
B
55

How about using "after" instead of "append".

$("#content ul li:last").after('<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>');

".after()" can insert content, specified by the parameter, after each element in the set of matched elements.

Berchtesgaden answered 18/1, 2012 at 7:6 Comment(2)
Thank you, this helped me. To insert into the middle of a list, you need to use before or after.Bunt
this combined with @Danubian_Sailor's answer hit the spot for meKeitel
O
30

jQuery comes with the following options which could fulfil your need in this case:

append is used to add an element at the end of the parent div specified in the selector:

$('ul.tabs').append('<li>An element</li>');

prepend is used to add an element at the top/start of the parent div specified in the selector:

$('ul.tabs').prepend('<li>An element</li>');

insertAfter lets you insert an element of your selection next after an element you specify. Your created element will then be put in the DOM after the specified selector closing tag:

$('<li>An element</li>').insertAfter('ul.tabs>li:last');
will result in:
<li><a href="/user/edit"><span class="tab">Edit</span></a></li>
<li>An element</li>

insertBefore will do the opposite of the above:

$('<li>An element</li>').insertBefore('ul.tabs>li:last');
will result in:
<li>An element</li>
<li><a href="/user/edit"><span class="tab">Edit</span></a></li>
Oxyhydrogen answered 30/9, 2014 at 12:58 Comment(0)
G
18

You should append to the container, not the last element:

$("#content ul").append('<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>');

The append() function should've probably been called add() in jQuery because it sometimes confuses people. You would think it appends something after the given element, while it actually adds it to the element.

Gisela answered 17/7, 2009 at 19:30 Comment(0)
S
7
$("#content ul").append('<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>');
Stupendous answered 17/7, 2009 at 19:29 Comment(1)
An explanation would be in order. For instance, user "Dipak" wrote: "Shouldn't it be '#header' instead of '#content'?"Nalley
D
7

Instead of

$("#header ul li:last")

try

$("#header ul")
Dody answered 17/7, 2009 at 19:32 Comment(0)
F
7

Use:

$("#content ul").append('<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>');

Here is some feedback regarding code readability (shameless plug for a blog). http://coderob.wordpress.com/2012/02/02/code-readability

Consider separating the declaration of your new elements from the action of adding them to your UL.. It would look something like this:

var tabSpan = $('<span/>', {
    html: 'Message Center'
});
var messageCenterAnchor = $('<a/>', {
    href='/user/messages',
    html: tabSpan
});
var newListItem = $('<li/>', {
    html: messageCenterAnchor,
    "id": "myIDGoesHere"
});    // NOTE: you have to put quotes around "id" for IE..

$("content ul").append(newListItem);
Failure answered 2/2, 2012 at 17:32 Comment(3)
var newListItem = $('<li/>', { html: messageCenterAnchor }); How do I get the li and id?Lettuce
@jmogera, are you trying to set the id? If so, you can just do that inside the { }'s. I updated the code above :)Failure
The link is (effectively broken): "Oops! That page can’t be found."Nalley
B
6

Use:

// Creating and adding an element to the page at the same time.
$("ul").append("<li>list item</li>");
Bullhorn answered 21/9, 2015 at 9:19 Comment(0)
M
4

This is the shortest way you can do that:

list.push($('<li>', {text: blocks[i] }));
$('ul').append(list);

Where blocks is an array. And you need to loop through the array.

Milda answered 25/5, 2016 at 3:24 Comment(0)
M
2

This is another one

$("#header ul li").last().html('<li> Menu 5 </li>');
Marrowfat answered 30/9, 2014 at 12:49 Comment(0)
B
1

Add li in ul as first item using prepend() function of jquery

$("ul").prepend("<li>first item</li>");

Add li in ul as last item using append() function of jquery

$("ul").append("<li>last item</li>");
Balaam answered 29/12, 2021 at 17:49 Comment(0)
A
0

Just to add to this thread - if you are moving an existing item you will need to use clone and then true/false on whether you clone/deep-clone the events as well (https://api.jquery.com/clone/).

Example: $("#content ul").append($('.existing_li').clone(true));

Alcoholometer answered 17/6, 2020 at 11:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.