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: Use the jQuery append() Method You can simply use the jQuery append() method to add <li> elements in an existing <ul> element.
$('<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 ).
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.
You can use $('li'). parent(). attr('id') to get the id of the parent element.
This would do it:
$("#header ul").append('<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>');   Two things:
<li> to the <ul> itself.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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With