DEV Community

Cover image for Create Image Elements in JavaScript
Raja Tamil
Raja Tamil

Posted on

Create Image Elements in JavaScript

In this JavaScript tutorial, you’re going to learn 14 common scenarios you’ll probably run into, if you have not already when working with images.

Show Image in Plain HTML

Create a static image tag with a src attribute with an image URL in the HTML file.



<img src="https://picsum.photos/200/300" />


Enter fullscreen mode Exit fullscreen mode

output:

alt text

As you can see, I use the picsum website for demonstration purposes. It lets me get a random image URL with specific dimensions passed at the end of the URL.

Pretty straight forward right?

Let’s see how to set a src attribute dynamically via JavaScript next.

Set Src Attribute in JavaScript

In the HTML file, create an HTML image tag like so:



<img/> 


Enter fullscreen mode Exit fullscreen mode

In JavaScript, get a reference to the image tag using the querySelector() method.



const img = document.querySelector("img"); 
img.src = "https://picsum.photos/200/301";


Enter fullscreen mode Exit fullscreen mode

Recommended → JS Variables

Then, assign an image URL to the src attribute of the image element.

Alternatively, you can set a src attribute to the image tag using the square brackets syntax like this:



img["src"] = "https://picsum.photos/200/301";


Enter fullscreen mode Exit fullscreen mode

output:

alt text

Set Multiple Src Attributes in JavaScript

Let’s say you have three image elements in the HTML page in different parts.



<img/> // image 1
...
<img/> // image 2
...
<img/> // image 2


Enter fullscreen mode Exit fullscreen mode

Using ID or class attribute, you can easily target each image element separately to set a different value to the src attribute which I will cover later in this chapter.

Let me show you what 🛑 NOT to do when having multiple static image tags in your HTML page.



const img = document.querySelector("img"); 


Enter fullscreen mode Exit fullscreen mode

In the previous example, I used the querySelector() method to target the image element which works fine for a single image element.

To get a reference to all three image elements, we’ll need to use querySelectorAll().



const img = document.querySelectorAll("img"); 


Enter fullscreen mode Exit fullscreen mode

This will get all of the image element references and create a Node List Array from them.



img[0].src = "https://picsum.photos/200/301"; // image 1
img[1].src = "https://picsum.photos/200/302"; // image 2
img[2].src = "https://picsum.photos/200/303"; // image 3


Enter fullscreen mode Exit fullscreen mode

This works fine, but there is a one problem with this approach.

Let’s say you no longer need the first image element and remove it from the HTML code.

Guess what?

The second and third image elements will end up having the first and second images.

Create Image Element in JavaScript

Create an image element using the createElement() method on the document object.

Then, set an image URL to its src attribute.



const img = document.createElement("img");
img.src = "https://picsum.photos/200/301";
document.body.appendChild(img);


Enter fullscreen mode Exit fullscreen mode

Finally, add the image element to the DOM hierarchy by appending it to the body element.

Alternatively, you can use the Image() constructor which creates a new HTMLImageElement instance and it’s functionally is equivalent to document.createElement(“img”).

Optionally, you can pass width and height parameters to it.



const img = new Image(100, 200); // width, height
img.src = "https://picsum.photos/200/301";
document.body.appendChild(img);


Enter fullscreen mode Exit fullscreen mode

It will be equivalent to this in HTML:



<img width="100" height="200" src="https://picsum.photos/200/301">


Enter fullscreen mode Exit fullscreen mode

Add Inline Style to the Image in JavaScript

Using the style property, we can apply style to the image element directly in JavaScript.

As you can see in the example below, I’ve applied a border as well as border radius styles to it.



let img = document.createElement("img");
img.src = "https://picsum.photos/200/301";

img.style.border = "10px solid orange";
img.style.borderRadius = "10px";

document.body.appendChild(img);


Enter fullscreen mode Exit fullscreen mode

alt text

Add ID Attribute to the Image in JavaScript

Adding multiple styles to the image element individually would be tedious.

Instead, let’s create a new CSS rule inside the style tags or an external CSS file with an ID selector like below.



#img-rounded-border {
  border:10px solid red;
  border-radius:10px;
}


Enter fullscreen mode Exit fullscreen mode

Then, assign it to the ID attribute of the image element using its ID property.



img.id = "img-rounded-border";


Enter fullscreen mode Exit fullscreen mode

As you know, it’s pretty straight forward as the value of the ID attribute should not be duplicated in a single page.

Alternatively, you can invoke the setAttribute() method on the img object with two arguments: the attribute name and the value.



img.setAttribute("id", "img-rounded-border");


Enter fullscreen mode Exit fullscreen mode

Add Class Attribute to the Image in JavaScript

Unlike ID attribute, you can add multiple class names in a single image element or the same class name in multiple image elements or combinations of both.

Let’s say we have a CSS rule with a class name called .img-rounded-border.



.img-rounded-border {
  border:10px solid red;
  border-radius:10px;
}


Enter fullscreen mode Exit fullscreen mode

Then, we can add this class to the image element using the add() method on the classList property passing the class name as an argument.

Continue Reading...

Top comments (0)