views:

41

answers:

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>
+7  A: 

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
That's great, thanks Nick. Any idea why I loose CSS formatting on my thumbs here: http://jsfiddle.net/Y2ER7/4/
FFish
@FFish - My fault, you need a `.parent()` in there to get the `<li>`, `.wrap()` returns the `<img>` otherwise, here's your fiddle updated: http://jsfiddle.net/Y2ER7/5/
Nick Craver
Nick = SuperHero. I found a sollution yself though. just addClass with the style for the thumbs. Cheers.
FFish
@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>`.
Nick Craver
A: 

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.

patrick dw
....why would you create one element with DOM methods, then another as a string inside it?
Nick Craver
@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 dw
@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 Craver
@Nick - Wouldn't the XSS issue be resolved since jQuery is (presumably) calling `.html()` to set the HTML content?
patrick dw
@patrick - Nope, that's exactly the issue, blindly doing `.innerHTML` :) `.text()`, etc encodes, as will an attribute, it'll take care of many attacks.
Nick Craver
@Nick - I see. I had thought that the point of using `.html()` was that it did something to protect against XSS. With regard to a quotation mark in `pic`, I can't find any way to produce an issue. Was there something specific you had in mind?
patrick dw