Reputation: 14783
I need some support with this one. I have an array:
var imageArr = [
{ someobject: '..', anotherobject: '..', img: 'SourceOfFirstImg.jpg'},
{ someobject: '..', anotherobject: '..', img: 'SourceOfSecondImg.jpg'},
// 100 times
]
and what I want to do is create an .each()
function to create <img>
elements, fill them with each link src and append them to a div. I does not need necessarely each()
if there is a plain JS way it is fine too.
How can I do this?
Upvotes: 0
Views: 64
Reputation: 700342
You can use the map
method to create an array of image elements to append:
$('.somediv').append($.map(imageArr, function(o){
return $('<img>', { src: o.img });
}));
Upvotes: 3
Reputation: 253318
At its simplest, I'd suggest:
var imageArray = [{
'alt': 'Alt text',
'src': 'http://placekitten.com/200/200',
'title': 'Title text'
}, {
'alt': 'More alt text',
'src': 'http://lorempixel.com/200/200',
'title': 'Yet another title attribute'
}],
target = document.body,
img;
imageArray.forEach(function(a){
img = document.createElement('img');
for (var prop in a) {
if (a.hasOwnProperty(prop)) {
img[prop] = a[prop];
}
}
target.appendChild(img);
});
Edited to use the OP's posted imageArr
:
var imageArr = [{
someobject: '..',
anotherobject: '..',
img: 'SourceOfFirstImg.jpg'
}, {
someobject: '..',
anotherobject: '..',
img: 'SourceOfSecondImg.jpg'
}],
target = document.body,
img;
imageArr.forEach(function (a) {
img = document.createElement('img');
img.src = a.img;
target.appendChild(img);
});
References:
Upvotes: 1
Reputation: 2328
Try this:
var imageArr = [
{ someobject: '..', anotherobject: '..', img: 'http://www.clipartbest.com/cliparts/Rcd/K5B/RcdK5Bbgi.png'},
{ someobject: '..', anotherobject: '..', img: 'http://www.clipartbest.com/cliparts/Rcd/K5B/RcdK5Bbgi.png'},
]
var div = document.createElement("div");
for(i = 0; i< imageArr.length; i++)
{
var img = document.createElement("img");
img.setAttribute("src",imageArr[i].img);
div.appendChild(img);
}
alert(div.innerHTML);
Upvotes: 0
Reputation: 17906
var imageArr = [
{ someobject: '..', anotherobject: '..', img: 'SourceOfFirstImg.jpg'},
{ someobject: '..', anotherobject: '..', img: 'SourceOfSecondImg.jpg'},
// 100 times
]
for (var i = 0; i < imageArr.length; i++) {
var img = $('<img class="foo" >');
img.attr('src', imageArr[i].img);
$('body').append(img);
};
Upvotes: 1