Home > Enterprise >  Image file name stored in array then displayed through loop
Image file name stored in array then displayed through loop

Time:08-31

I've correctly did this with displaying text in a p tag but i can't figure out why my image won't show up in the same manner and I'm not sure if it has to do with how it was set up in html.

let imgArray = ["beastiary.jpg"];

window.addEventListener("load", showImages);

function showImages() {
    let i = 0;

    let images = document.getElementsByTagName("img");

    while (i < imgArray.length) {
        images[i].innerHTML = imgArray[i]

        i  
    }

}
 <div  style="padding-right: 5px">
                        <div  id="book">
                           <img src="" alt="book">
                            <div >
                                <p></p>
                            </div>
                        </div>

                    </div>

I have tried to do away with using img and instead put it in a div using an id but it still won't show up. There will be more images I'm just making sure this one works first before I start adding the rest.

CodePudding user response:

For showing image you need to set src to proper url

let imgArray = ["https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/800px-Image_created_with_a_mobile_phone.png"];

window.addEventListener("load", showImages);

function showImages() {
  let i = 0;

  let images = document.getElementsByTagName("img");

  while (i < imgArray.length) {
    images[i].src = imgArray[i]
    i  
  }

}
.img {
  width: 200px;
  height: 200px;
}
<img class='img'/>

  • Related