Exploring How JavaScript Change Image src | 3 Methods

In this article, we’ll explore three methods to change image src using JavaScript.

From directly manipulating the src property to using the HTML DOM, we’ll equip you with the knowledge to transform your images effectively.

Why use JavaScript to change image src?

JavaScript is used to change the source (src) of an image on a website. It enables dynamic content, so images can be updated based on user interactions or events.

JavaScript also helps in creating responsive designs, adapting images for different devices. It allows for preloading and lazy loading, improving loading times and performance.

Additionally, JavaScript is useful for building image galleries and slideshows with smooth transitions. It can fetch images from external sources, making it versatile for various web development needs.

How to change image src in JavaScript

To change the image source (src) using JavaScript, there are a few different methods you can use.

Here are three common approaches:

Method 1: Changing the src Property

You can directly modify the src property of an image element using JavaScript.

Meanwhile, the src property is used to get or set the URL of the image source.

Example Program:

<!DOCTYPE html>
<html>
<body>

<h2>Change Image Source</h2>

<img id="myImage" src="image1.jpg" width="200" height="100">

<button onclick="changeImageSrc()">Change Image Source</button>

<script>
function changeImageSrc() {
  var image = document.getElementById("myImage");
  image.src = "image2.jpg";
}
</script>

</body>
</html>

When you first load the webpage, you’ll see an image displayed with the source set to “image1.jpg”.

However, when you click the button, it triggers a function called changeImageSrc().

Inside this function, the src property of the image is modified and set to “image2.jpg”. As a result, the image on the webpage gets replaced with the new source, “image2.jpg”.

So, after clicking the button, you’ll see a different image shown on the webpage.

Method 2: Modifying the Attribute

Another approach is to modify the src attribute of the image element using the setAttribute() method.

The setAttribute() method is used to set the value of an attribute on the specified element.

Example Program:

<!DOCTYPE html>
<html>
<body>

<h2>Change Image Source</h2>

<img id="myImage" src="image1.jpg" width="200" height="100">

<button onclick="changeImageSrc()">Change Image Source</button>

<script>
function changeImageSrc() {
  var image = document.getElementById("myImage");
  image.setAttribute("src", "image2.jpg");
}
</script>

</body>
</html>

In this program, when you click a button, the image source is changed. Initially, the image is set to “image1.jpg,” but when the button is clicked, it gets updated to “image2.jpg.”

This means that when you interact with the button, the image on the webpage will change to a different picture.

Method 3: Using the HTML DOM

You can also change the image source using the HTML DOM (Document Object Model) by accessing the src property of the image element.

The HTML DOM is a programming interface for HTML documents. It represents the page so that JavaScript can change and interact with the content.

Example Program:

<!DOCTYPE html>
<html>
<body>

<h2>Change Image Source</h2>

<img id="myImage" src="image1.jpg" width="200" height="100">

<button onclick="changeImageSrc()">Change Image Source</button>

<script>
function changeImageSrc() {
  var image = document.getElementById("myImage");
  image.src = "image2.jpg";
}
</script>

</body>
</html>

In this program, when you click a button, the image on the webpage will change. Initially, the image is set to “image1.jpg.”

However, as soon as you interact with the button by clicking it, the image source will be updated to “image2.jpg.”

This means that you’ll see a different image displayed on the webpage once you click the button.

To learn more about JavaScript functions here are other resources you can check out:

Conclusion

In conclusion, this article explored three methods to change the image src using JavaScript. JavaScript is a powerful scripting language that enhances user experiences and adds interactivity to websites.

By dynamically modifying the src attribute, developers can create captivating web applications that respond promptly to user actions.

The three methods discussed include directly manipulating the src property, modifying the attribute using the setAttribute() method, and leveraging the HTML DOM.

Each method equips developers with the knowledge and tools needed to effectively transform images.

Using JavaScript to change image src offers flexibility and adaptability, allowing developers to update images in response to various user interactions and event-driven triggers.

By harnessing the power of JavaScript, developers can take their image transformations to the next level and create engaging web experiences.

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.
Glay Eliver

Programmer & Technical Writer at PIES IT Solution

Glay Eliver is a programmer and writer at PIES IT Solution, author of over 600 tutorials at itsourcecode.com. Specializes in JavaScript tutorials, Microsoft Office how-tos (Excel, Word, PowerPoint), and Python error debugging covering ImportError, TypeError, AttributeError, ModuleNotFoundError, and JavaScript ReferenceError. Authored several of the site’s highest-traffic Excel and MS Office reference articles.

Expertise: JavaScript · MS Excel · MS Word · MS PowerPoint · Python · Python ImportError · Python TypeError · Python AttributeError · ModuleNotFoundError · JavaScript ReferenceError · Pygame  · View all posts by Glay Eliver →

Leave a Comment