Eileen Eileen - 1 year ago 48
jQuery Question

jQuery: how to add <li> in an existing <ul>?

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>

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
inside the last
(just before the closing tag), not after it. What's the best way to add this


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.