mchd
mchd

Reputation: 3163

Images from a JS for-loop do not load up on HTML

I have an array of images in JS that I need to contain in HTML. This is my array and the JS code:

// Data for the "HTML Images" Page

var images = [
    {caption: "Red Slate Mountain", alt: "Mountain", url: "https://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Red_Slate_Mountain_1.jpg/320px-Red_Slate_Mountain_1.jpg"},
    {caption: "St. Petersburg River", alt: "River", url: "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Saint-petersburg-river-march-24-2016.jpg/320px-Saint-petersburg-river-march-24-2016.jpg"},
    {caption: "Lybian Desert", alt: "Desert", url: "https://upload.wikimedia.org/wikipedia/commons/thumb/9/99/Libyan_Desert_-_2006.jpg/320px-Libyan_Desert_-_2006.jpg"},
    {caption: "Azerbaijan Forest", alt: "Forest", url: "https://upload.wikimedia.org/wikipedia/commons/thumb/6/6d/Azerbaijan_forest_3.JPG/320px-Azerbaijan_forest_3.JPG"},
    {caption: "Indonesian Jungle", alt: "Jungle", url: "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f5/Indonesian_jungle3%2C_Zoo_Prague.jpg/320px-Indonesian_jungle3%2C_Zoo_Prague.jpg"}
];

window.onload = function(){
    var figure = "<figure>";
    for(var i = 0; i <= images.length; i++){
        figure += '<img src="'+ images[i].url + '" ' + 'alt="' + images[i].alt + '">' 
        + '<figcaption>' + images[i].caption + "</figcaption>"   
    }figure += "</figure>";

    var myContainer = document.querySelector("#image").innerHTML = figure;
}

and this is the HTML container:

<section class="main center">

            <h2>HTML Images</h2>
            <a href="https://ict.senecacollege.ca/" target="_blank">
                <img src="assignment3/img/ict.png">
            </a>
            <h2>Scenes</h2>
            <div id="image"></div>

    </section>

But the page is blank. I am assuming that the issue is my concatenation but I couldn't find an error with it.

Upvotes: 1

Views: 78

Answers (3)

HMR
HMR

Reputation: 39320

You could also reduce the array to a string:

const figure = images.reduce(
  (all,image)=>
    all + '<img src="'+ image.url + '" ' + 'alt="' + image.alt + '">' 
    + '<figcaption>' + image.caption + "</figcaption>",
  "<figure>"//initial value
) + "</figure>";

Upvotes: 1

Ian Middelkamp
Ian Middelkamp

Reputation: 140

You are iterating once more than necessary due to the equals sign and it is causing an error. an array of length 6 has its last element at 5.

Upvotes: 1

Daniel Thompson
Daniel Thompson

Reputation: 2351

There are 5 items in the array 'images'. Your loop starts at 0 and goes up until and including 5, which is 6 iterations.

you want i < images.length

you are currently accessing .url of undefined (the default value for an index that does not exist)

Upvotes: 3

Related Questions