Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a list item to an existing unordered list

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?

like image 766
Eileen Avatar asked Jul 17 '09 19:07

Eileen


People also ask

How do I add an item to a list in UL?

Answer: Use the jQuery append() Method You can simply use the jQuery append() method to add <li> elements in an existing <ul> element.

How do you append to a list in HTML?

$('<li>Your text</li>'). appendTo('#everything'); The advantage of using this method is that you can append the item element to an unordered HTML list ( ul ), or an ordered HTML list ( ol ).

How do you make an unordered list in HTML?

To create unordered list in HTML, use the <ul> tag. The unordered list starts with the <ul> tag. The list item starts with the <li> tag and will be marked as disc, square, circle, etc. The default is bullets, which is small black circles.

How can get ul id in jQuery?

You can use $('li'). parent(). attr('id') to get the id of the parent element.


2 Answers

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.
like image 51
Paolo Bergantino Avatar answered Sep 23 '22 02:09

Paolo Bergantino


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 :)

like image 28
Danubian Sailor Avatar answered Sep 25 '22 02:09

Danubian Sailor