Member-only story
JavaScript Working With Images

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.
1. Show Image in Plain HTML
Create a static image tag with an src attribute with an image URL in the HTML file.
<img src="https://picsum.photos/200/300" />
output:
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 an src attribute dynamically via JavaScript next.
2. Set Src Attribute In JavaScript
In the HTML file, create an HTML image tag like so:
<img/>
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";
Recommended → JS Variables
Then, assign an image URL to the src attribute of the image element.
Alternatively, you can set an src attribute to the image tag using the square brackets syntax like this:
img["src"] = "https://picsum.photos/200/301";
output:
3. Set Multiple Src Attributes In JavaScript
Let’s say you have three image elements on the HTML page in different parts.
<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 on your HTML page.
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.