Reputation: 1654
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 ?
Upvotes: 0
Views: 105
Reputation: 415
$("#test-ul").append("html here"); // after the last li
$("#test-ul").prepend("html here"); // before the first
Upvotes: 1
Reputation: 103428
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);
});
Upvotes: 2
Reputation: 47300
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);
Upvotes: 0
Reputation: 14219
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);
});
Upvotes: 0
Reputation: 15200
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.
Upvotes: 4