supersize
supersize

Reputation: 14783

each function to create img elements out of array

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

Answers (4)

Guffa
Guffa

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

David Thomas
David Thomas

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);
});

JS Fiddle demo.

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);
});

JS Fiddle demo.

References:

Upvotes: 1

super
super

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);

Here is the Demo

Upvotes: 0

john Smith
john Smith

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

Related Questions