How Change The Image Source Attribute Using Javascript
In this easy tutorial i will be showing you how JavaScript changes the value of the src (source) attribute of an img tag.JavaScript can change any kind of HTML element on a webpage because it has One of many JavaScript HTML methods called getElementById().
This example uses the method to find an HTML element with id=”bulb” and changes the image src (source) attribute to a given image.
Absorbing this amount of content would be alot if you are just reading it,so i have put together a very simple video for you to understand the code below.
Simple HTML code – copy to text Editor
<!DOCTYPE html>
<html>
<head>
<title>Javascript</title>
<style>
.container{
display:flex;
height:100vh;
}
.controllers{
margin:auto;
}
</style>
</head>
<body>
<div class=”container”>
<div class=”controllers”>
<button id=”On”>Switch on</button>
<img id=”bulb”>
<button id=”Off”>Switch off</button>
</div>
</div>
</body>
</html>
Javascript Code
//Initialize the default bulb
document.getElementById(‘bulb’).src=’img/bulboff.gif’;
//Grab on the switch on btn and add an event(click)
document.getElementById(‘On’).addEventListener(‘click’,switchOn);
//Grab on the switch off btn and add an event(click)
document.getElementById(‘Off’).addEventListener(‘click’,switchOff);
//Runs when the switch on button is clicked
function switchOn(){
let On = document.getElementById(‘bulb’);
On.src = ‘img/bulbon.gif’;
}
//Runs when the switch off button is clicked
function switchOff(){
let Off = document.getElementById(‘bulb’);
Off.src = ‘img/bulboff.gif’;
}
To download source code: click here description
account_box Author: Osto Code
date_range Date: 7th, March 2026
access_time Time: 8:58 pm
remove_red_eye Views: 22 Views