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>

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

That's great, thanks Nick. Any idea why I loose CSS formatting on my thumbs here: jsfiddle.net/Y2ER7/4
@FFish - My fault, you need a .parent() in there to get the <li>, .wrap() returns the <img> otherwise, here's your fiddle updated: jsfiddle.net/Y2ER7/5
Nick = SuperHero. I found a sollution yself though. just addClass with the style for the thumbs. Cheers.
@FFish - Make sure to use .parent()!, without it you're appending a <img> to a <ul> which is invalid, it needs to be in a <li>.
0

You could do something like this: http://jsfiddle.net/Y2ER7/6/

$("<li />", {html:"<img src='" + pic + "' />"}).appendTo("#album ul");

Creates a new <li> element, with its HTML content set as the <img> with pic concatenated in for the src attribute.


EDIT: As described in the comments from @Nick Craver below, if you're unsure of the source of your pic variable, you should not concatenate the src attribute as in this answer.

If you're using a string as in your question, there shouldn't be an issue.

7 Comments

....why would you create one element with DOM methods, then another as a string inside it?
@Nick - Lack of experience? :o) I figured there must be some reason why jQuery made the html: option available, but perhaps it is better to not use it?
@patrick - Just be aware of the dangers, e.g. pic having a quote in it, XSS attach, etc, better to create one way or another, and DOM is always the safer route :)
@Nick - Wouldn't the XSS issue be resolved since jQuery is (presumably) calling .html() to set the HTML content?
@patrick - Nope, that's exactly the issue, blindly doing .innerHTML :) .text(), etc encodes, as will an attribute, it'll take care of many attacks.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.