2

How can I append this URL variable to the list?

I am fiddling around with this: http://jsfiddle.net/Y2ER7/4/

JS:

$(function() {
    var pic = "http://jqueryui.com/demos/droppable/images/high_tatras3_min.jpg";

    // doesn't work
    $("<li><img /></li>").attr("src", pic).appendTo("#album ul");
    $("<li><img src='pic' /></li>").appendTo("#album ul");

    // hardcoded works
    $("<li><img src='http://jqueryui.com/demos/droppable/images/high_tatras3_min.jpg' /></li>").appendTo("#album ul");
});

HTML:

<div id="album">
    <ul>
        <li>red</li>
        <li>green</li>
        <li>blue</li>
    </ul>
</div>
FFish
  • 10,964
  • 34
  • 95
  • 136

2 Answers2

9

You want to set the src on the <img> so do that then .wrap() it in a <li></li>, like this:

$("<img />").attr("src", pic).wrap("<li />").parent().appendTo("#album ul");

You can test it out here, make sure to use .parent() to get the <li> you wrapped it in.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • That's great, thanks Nick. Any idea why I loose CSS formatting on my thumbs here: http://jsfiddle.net/Y2ER7/4/ – FFish Sep 28 '10 at 17:28
  • @FFish - My fault, you need a `.parent()` in there to get the `
  • `, `.wrap()` returns the `` otherwise, here's your fiddle updated: http://jsfiddle.net/Y2ER7/5/
  • – Nick Craver Sep 28 '10 at 17:33
  • Nick = SuperHero. I found a sollution yself though. just addClass with the style for the thumbs. Cheers. – FFish Sep 28 '10 at 17:35
  • 2
    @FFish - Make sure to use `.parent()`!, without it you're appending a `` to a `
      ` which is invalid, it needs to be in a `
    • `.
    – Nick Craver Sep 28 '10 at 17:36