Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery use variable in string for appendTo

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>
like image 950
FFish Avatar asked Feb 27 '26 19:02

FFish


1 Answers

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.

like image 55
Nick Craver Avatar answered Mar 01 '26 09:03

Nick Craver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!