Categories
JavaScript Answers

How to Create an img Element with JavaScript?

Spread the love

One way to create an img element with JavaScript is to use the Image constructor.

For instance, we can write:

const img = new Image(200, 300);  
img.src = 'https://i.picsum.photos/id/487/200/300.jpg?hmac=jDYxTxKFMi18Gu5h9qt9ttwJKCk1-J6bZeHDtXGL2Vk';  
document.body.appendChild(img)

We use the Image constructor with 2 arguments to create an img element.

The arguments are the width and height respectively.

Then we set the src property to the image URL to set the src attribute value.

And then we call document.body.appendChild with img to append it to the body.

Create an img Element with JavaScript with the document.createElement Method

Another way to create an img element with JavaScript is to use the document.createElement method.

For instance, we can write:

const img = document.createElement('img');  
img.src = 'https://i.picsum.photos/id/487/200/300.jpg?hmac=jDYxTxKFMi18Gu5h9qt9ttwJKCk1-J6bZeHDtXGL2Vk';  
document.body.appendChild(img)

to use:

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

to create an img element.

And the rest of the code is the same.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *