A.Ridley
A.Ridley

Reputation: 63

Output an array of images in JavaScript

I'm new to JavaScript and I made this code. The purpose of this code is to use JavaScript and HTML to display an ARRAY of images in a website. They all need to be displayed at once. This is the code so far, however it is not working.

<html>
<head>
<script>
        var ArrayOfImages = [];

        var Image1 = new Image1()
        image1.src = "image1.jpg";

        var Image2 = new Image2()
        Image2.src = "image2.jpg";

        var Image2 = new Image3()
        Image3.src = "image3.jpg";

        ArrayOfImages.push(Image1);
        ArrayOfImages.push(Image2);
        ArrayOfImages.push(Image3);
        ArrayOfImages.toString();
        document.write(ArrayOfImages);
</script>
</head>
<body>
</body>
</html>

When I run this code all I get is an empty webpage.

For anyone wondering, the images are in the same file as the html file. I'm also relatively new to JavaScript and HTML so please be clear in how to fix it.

Upvotes: 0

Views: 11935

Answers (1)

Hikmat Sijapati
Hikmat Sijapati

Reputation: 6969

You have to use array.forEach then append each array item in body.Like this

var ArrayOfImages = ['image1.jpg', 'image2.jpg', 'image3.jpg']; //your assumed array
ArrayOfImages.forEach(function(image) {    // for each link l in ArrayOfImages
  var img = document.createElement('img'); // create an img element
  img.src = image;                         // set its src to the link l
  document.body.appendChild(img);          // append it to the body 
});

See Fiddle: Fiddle

UPDATE

You can also set height and width as your requirement.Like below.

var ArrayOfImages = ['https://upload.wikimedia.org/wikipedia/commons/f/f9/Wiktionary_small.svg', 'https://upload.wikimedia.org/wikipedia/commons/f/f9/Wiktionary_small.svg', 'https://upload.wikimedia.org/wikipedia/commons/f/f9/Wiktionary_small.svg']; //your assumed array
ArrayOfImages.forEach(function(image) {
  var img = document.createElement('img');
  img.src = image;
  img.height = "45";
  img.width = "50";
  document.body.appendChild(img);
});

Upvotes: 3

Related Questions