I have a menu:
<ul id="test-ul">
<li>test</li>
<li>test2</li>
</ul>
How do i add the following HTML markup before the first li and after the last li:
<li class="first">
<img src="http://i48.tinypic.com/sosmck.jpg" width="27" height="15" />
</li>
<li class="last">
<img src="http://i48.tinypic.com/sosmck.jpg" width="27" height="15" />
</li>
using jquery ?
asked Jun 19, 2012 at 12:46
SOLDIER-OF-FORTUNE SOLDIER-OF-FORTUNESOLDIER-OF-FORTUNE
1,6445 gold badges39 silver badges68 bronze badges
5 Answers 5
This isn't valid syntax to add div
in ul
tag. But to undeerstand concept of adding html via Jquery, here you go
var str = '<div class="first"><img src="http://i48.tinypic.com/sosmck.jpg" width="27" height="15" /></div><div class="last"><img src="http://i48.tinypic.com/sosmck.jpg" width="27" height="15" /></div>';
$("#test-ul").append(str).prepend(str);
You can see Jsfiddle example here.
answered Jun 19, 2012 at 12:50
-
1@Simon got it first, but your solution is much more elegant! And it has a jsFiddle!.Ayman Safadi– Ayman Safadi2012年06月19日 12:52:06 +00:00Commented Jun 19, 2012 at 12:52
-
I don't see it is more elegant. It does the same. At least it adds
div
s with the same class names.VisioN– VisioN2012年06月19日 12:56:32 +00:00Commented Jun 19, 2012 at 12:56 -
On second thoughts I think this might not be quite what the OP is after. I think the OP would wants the
first
element before theli
s and thelast
element after theli
sCurtis– Curtis2012年06月19日 12:58:38 +00:00Commented Jun 19, 2012 at 12:58 -
1accepted because you have chuck norris as your name and the example helped me alot! :)SOLDIER-OF-FORTUNE– SOLDIER-OF-FORTUNE2012年06月19日 14:48:40 +00:00Commented Jun 19, 2012 at 14:48
You shouldn't add these elements before and after li
. Any element other than li
nested in a ul
is invalid HTML.
You could however add the content within a new li
, this would be valid.
$(function(){
var $li = $("<li></li>");
$li.html("html code...");
$("#test-ul").append($li);
var $li2 = $("<li></li>");
$li2.html("different html code..");
$("#test-ul").prepend($li2);
});
answered Jun 19, 2012 at 12:48
$("#test-ul").append("html here"); // after the last li
$("#test-ul").prepend("html here"); // before the first
VisioN
146k34 gold badges287 silver badges291 bronze badges
answered Jun 19, 2012 at 12:48
If you want to create a new LI for each, this would work. Be aware if you add more divs it will cause issues.
$('div').each(function() {
var newli = $(this).html().wrap('<li></li>');
$('#test-ul').append(newli);
});
answered Jun 19, 2012 at 12:51
var first = '<li<img src="/sosmck.jpg" width="27" height="15" /></li>';
var last = '<li><img src="/sosmck.jpg" width="27" height="15" /></li>';
var myItems = $("li");
myItems.prepend(first);
myItems.append(last);
answered Jun 19, 2012 at 12:53
lang-js
ul
) should contain onlyli
elements inside.$("#test-ul").append("<li />");
$("#test-ul").prepend("<li />");