How To Dynamically Add Images With Javascript

In this tutorial, we will learn to add images dynamically with javascript in html.

We can divide the tutorial in 3 steps.

  • First – Create Image Element
  • Second – Set Attributes
  • Third – Append to an Element

HTML

<div class="container">
  <div class="image_container"></div>
</div>
<script src="index.js"></script>

JS

const images = ['images/1.jpg',
    'images/2.jpg',
    'images/3.jpg',
    'images/4.jpg',
    'images/5.jpg',
    'images/6.jpg',
    'images/7.jpg',
    'images/8.jpg',
    'images/9.jpg'
]

let image_container = document.querySelector('.image_container');

images.forEach((e, i) => {
    let imgElem = document.createElement("img");
    imgElem.setAttribute("src", images[i]);
    imgElem.setAttribute("height", "350");
    imgElem.setAttribute("width", "350");
    image_container.append(imgElem);
})