tags:

views:

5653

answers:

4

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?

+2  A: 
$("#content ul").append('<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>');
Evan Meagher
+13  A: 

This would do it:

$("#content 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.
Paolo Bergantino
Perfect, thanks! (Yeah, I noticed that about the quotes -- they are right in the actual code.)
Eileen
+1  A: 

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.

Philippe Leybaert
+4  A: 

Instead of

$("#header ul li:last")

try

$("#header ul")
Adrian Godong