DEV Community

Cover image for How to create an image element using JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to create an image element using JavaScript?

Originally posted here!

Using the Image() constructor function

To create an image element using JavaScript, you can use the Image() constructor function available in the global window object.

// create an image element
const image = new Image();
Enter fullscreen mode Exit fullscreen mode

The constructor function accepts 2 parameters:

  • The first parameter is the width of the image
  • The second parameter is the height of the image
// create an image element
const image = new Image(200, 200);
Enter fullscreen mode Exit fullscreen mode

Now we need to specify a source for the image element, you can do that using the src property in the image object.

// create an image element
const image = new Image(200, 200);

// source for the image element
// source means the link to the image
image.src = "https://via.placeholder.com/200";
Enter fullscreen mode Exit fullscreen mode

You can add attributes to the image element using the dot . followed by the name of the attribute.

For example, to add alt attribute, you can use the alt property in the image object like this,

// create an image element
const image = new Image(200, 200);

// source for the image element
// source means the link to the image
image.src = "https://via.placeholder.com/200";

// adding alt attribute
image.alt = "A simple placeholder image";
Enter fullscreen mode Exit fullscreen mode

Using the document.createElement() function

You can alternatively create image elements using the document.createElement() method like this,

// create image element
const image = document.createElement("img");
Enter fullscreen mode Exit fullscreen mode
  • The method needs a valid tag name as a string.

To add src and alt tag you need to use the dot . operator followed by attribute name like this,

// create image element
const image = document.createElement("img");

// add attributes src and alt
image.src = "https://via.placeholder.com/200";
image.alt = "A simple placeholder image";
Enter fullscreen mode Exit fullscreen mode

See live example on both ways in JSBin

Feel free to share if you found this useful 😃.


Top comments (0)