How to add a list item to an existing unordered list?

Eileen picture Eileen · Jul 17, 2009 · Viewed 773k times · Source

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?

Answer

Paolo Bergantino picture Paolo Bergantino · Jul 17, 2009

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.