Tyler Ramsey
Tyler Ramsey

Reputation: 31

Take a src img from a javascript object and put it in HTML

I'm working on a program that picks an object from an array and displays a picture to a div. How could I take a picture from an object and display it? I was thinking something like this but it doesn't seem to work.

var pizza = {
crust: bread,
topping: sauce,
imgURL: 'www.pizza.com'
} 

$('#mydiv').append(pizza.imgURL);

Upvotes: 0

Views: 52

Answers (2)

Mark Santiago
Mark Santiago

Reputation: 463

Have you tried this?

$('#mydiv').append('<img src="' + pizza.imgURL + '"/>');

This appends an image in your #myDiv and sets it's image-source-url based on your pizza object

Upvotes: 1

caleb531
caleb531

Reputation: 4361

A solid solution would be to create the element via jQuery, set its src to pizza.imgURL, and pass the element to the append() method. This ensures that the URL is properly escaped (it shouldn't be an issue, but it's certainly possible).

Here's a jsFiddle to prove that this works. However, of course, the image doesn't load because, well, it's not a valid image URL.

var pizza = {
    crust: bread,
    topping: sauce,
    imgURL: 'www.pizza.com'
} 

$('#mydiv').append($('<img>').prop({
    src: imgURL,
    // don't forget your alt attribute!
    alt: 'pizza'
}));

Upvotes: 0

Related Questions