Create Image Elements in JavaScript
Tags: javascript, programming
Published: 2021-08-30 12:44:35

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.

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

**output:**

![alt text](https://i.picsum.photos/id/387/200/300.jpg?hmac=JlKyfJE4yZ_jxmWXH5sNYl7JdDfP04DOk-hye4p_wtk)

>*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:

```HTML
<img/> 
```

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

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

>*Recommended → [JS Variables](https://softauthor.com/category/javascript/)*

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:

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

**output:**

![alt text](https://i.picsum.photos/id/841/200/300.jpg?hmac=G9hBg_h2jvXDwBgnqCm8LO9PXRrPRWbz1xgdUrMf1Y8)

###Set Multiple Src Attributes in JavaScript

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

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

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.

```JavaScript
const img = document.querySelector("img"); 
```
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()**.

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

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

```JavaScript
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
```

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.

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

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.

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

It will be equivalent to this in HTML:

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

###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.

```JavaScript
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);
```

![alt text](https://softauthor.com/wp-content/uploads/2020/07/js-images-add-inline-style.png)

###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.

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

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

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

>*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**.

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

###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.

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

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...](https://softauthor.com/javascript-working-with-images/)