SOLDIER-OF-FORTUNE
SOLDIER-OF-FORTUNE

Reputation: 1654

adding HTML using jquery

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

Answers (5)

Simon
Simon

Reputation: 415

$("#test-ul").append("html here");    // after the last li

$("#test-ul").prepend("html here");   // before the first

Upvotes: 1

Curtis
Curtis

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); 
});​

SEE EXAMPLE

Upvotes: 2

NimChimpsky
NimChimpsky

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

Terry
Terry

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

Chuck Norris
Chuck Norris

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

Related Questions