Author Photo
Christopher Unum I am a software Developer, I write web development tutorials, I also mentor aspiring web developers. s

how to add images dynamically on webpage using javascript

Loading images dynamically on the web can be very useful, especially when you are retrieving the images from a server or an API. In this tutorial, we will learn how to render images on the web from a list of images saved in an array. The interface above is fully function, feel free to try it out.


Basic knowledge of Html, CSS, and JavaScript are required to fully understand the concepts in this tutorial.


To begin, we need to write Html code upon which we will render our images.

<div id="board">
  <div id="images-container">
    <div id="image-out">
      <div id="image-in">
        <img src="images/image10.jpg" />
  <button id="add-image">Add Image</button>


Now we style the Html, giving it a better look and feel. We added a media query that changes the width of the images when the width of the screen approaches 390px.

  margin20px auto;
  margin:2px 0;
  margin:0 auto;
#image-in img{
  padding5px 12px;
  margin20px 0;

@media only screen and (max-width:390px){


Now to make the Add Image button work, we will be adding some JavaScript code.

//array of images
const images = ['images/image1.jpg','images/image2.jpg','images/image3.jpg','images/image4.jpg','images/image5.jpg','images/image6.jpg','images/image7.jpg','images/image8.jpg','images/image9.jpg','images/image10.jpg'];

//listens for clicks
document.querySelector("#add-image").addEventListener("click", () => {

//aids in looping through the array
let x = 0;
const addImage = () => {
  //creates a div element
  let imageOut = document.createElement("div");
  //sets the id of the div
  let imageIn = document.createElement("div");
  //cereates an image element
  let img = document.createElement("img");
  //adds image to the image element


  //aids in looping through the array indefinitely
  if(x==10) x=0;


We've come to the end of this tutorial, hope you were able to learn something new. you can leave a comment in the comments area if you need help.