/

How to Add an Image to the DOM using JavaScript

How to Add an Image to the DOM using JavaScript

Adding an image dynamically to an HTML page, or the DOM, can be done programmatically using JavaScript. In this article, we will go through the steps to achieve this.

To begin, we need to create an img element using the createElement method of the Document object:

1
const image = document.createElement('img');

Next, we set the src attribute of the image to specify the image URL:

1
image.src = '/picture.png';

You can use either a relative or an absolute URL, just like you would in a regular HTML img tag.

Finally, we need to identify the container where we want to append the image and use the appendChild() method:

1
document.querySelector('.container').appendChild(image);

By following these steps, you can dynamically add an image to the DOM using JavaScript.

tags: [“JavaScript”, “DOM manipulation”, “image manipulation”]