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
?
This is another one
You should append to the container, not the last element:
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.
easy
How about using "after" instead of "append".
".after()" can insert content, specified by the parameter, after each element in the set of matched elements.
You can do it also in more 'object way' and still easy-to-read:
You don't have to fight with quotes then, but must keep trace of braces :)
jQuery comes with the following options which could fulfil your need in this case:
append
is used to add an element at the end of the parentdiv
specified in the selector:prepend
is used to add an element at the top/start of the parentdiv
specified in the selector:insertAfter
lets you insert an element of your selection next after an element you specify. Your created element will then be put in the DOM after the specified selector closing tag:insertBefore
will do the opposite of the above: