How to Change Img Src using JavaScript
Table of Contents
The cool thing about JavaScript is that you can use it to programmatically alter the DOM.
This includes the ability to change an image's src
attribute to a new value, allowing you to change the image being loaded.
In this post, we will learn how we can use JavaScript to change the src
attribute of an image.
Chaning an Image's src
Attribute
Let's assume this is our DOM:
HTML<img src="cat.png" class="image" />
The first step is to query the DOM for this image. We can do this by using the querySelector()
method.
JAVASCRIPTconst image = document.querySelector(".image");
Now that we have our element, we can change the src
attribute of the image.
JAVASCRIPTconst image = document.querySelector(".image");
image.src = "dog.png";
This turns the DOM into this:
HTML<img src="dog.png" class="image" />
On Load
Sometimes, you want to run some code after the image has loaded. Thankfully, this is easily accomplished by simply adding an event listener to the image.
JAVASCRIPTconst image = document.querySelector(".image");
image.addEventListener("load", () => {
console.log("The image has loaded!");
});
Now, when the image has loaded, the function will execute, printing to the console. You can do whatever you want, including changing the src
attribute of the image to another image.
Conclusion
In this post, we've seen how we can use JavaScript to change the src
attribute of an image.
If you want, you can also run some code after the image has loaded.
Hopefully, you've enjoyed this post, thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Svelte
- Getting Started with Express
- Getting Started with Electron
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- Learn how to use v-model with a custom Vue component
- Getting Started with Handlebars.js
- Getting Started with Vuex: Managing State in Vue
- Using Axios to Pull Data from a REST API