Jerry Svensson Jerry Svensson - 5 months ago 24
jQuery Question

Append img tag with src from a JavaScript object?

I'm trying fetch to add an image from a Javascript Object and wrap it in an img tag - how do I do this correctly? Adding just img as an element doesn't work so whats the best way to do this?

Fiddle: https://jsfiddle.net/hszxbmrx/6/

Javascript Object:

var retailerData = {
"del": {
"zip": "",
"city": ""
},
"user": {
"country": "",
"phone": "",
"nbrOrders": 0,
"name": "",
"salesPerson": "",
"customerNo": "",
"email": ""
},
"order": {
"shippingSum": 0.0,
"orderno": "0",
"voucher": "",
"currency": "SEK",
"orderVat": 3322.5,
"orderSum": 13290.0,
"items": [{
"qtyAvail": 0,
"imageURI":"http://www.windowspasswordsreset.com/windows-password-knowledge/images/dell-laptop.jpg",
"price": 6295.0,
"qty": 1,
"id":"244992",
"artno": "DEL-17812033.10-4",
"label": "E7240/i5-4310U/4GB1/128SSD/12,5HD(1366x768)/W7P 3-Cell/CAM/3YRNBD/W8.1P/US int Keyboard",
"category": "Computers - Notebooks",
"manufacturer": "Dell"
}, {
"qtyAvail": 31,
"imageURI":"http://www.windowspasswordsreset.com/windows-password-knowledge/images/dell-laptop.jpg",
"price": 6995.0,
"qty": 1,
"artno": "20BV001KUK",
"label": "Lenovo ThinkPad T450 20BV - 14" - Core i3 5010U - 4 GB RAM - 500 GB Hybrid Drive",
"category": "Computers - Notebooks",
"manufacturer": "Lenovo"
}]
}
}


Script:

$.each(retailerData.order.items,function(i,v){//get the item
var div = $('<div class="test">')
div.append('item '+ '<img>'+ v.imageURI+'</img>' + '<span class="art">'+ v.artno+'</span>' + '<span class="price">'+ v.price+'</span>' )
$('.carttable').append(div)
})

Answer

The URL of the <img /> should be placed in the src property, and the element is self closing; it does not have a separate closing tag. Try this:

div.append('item <img src="' + v.imageURI + '" /><span class="art">' + v.artno + '</span><span class="price">' + v.price + '</span>')

Updated fiddle

Also note that you don't need to append string literals together, you can just use a single string.