How to replace an existing image in a HTML page using javascript ?

Published: February 19, 2021

Tags: Javascript;

DMCA.com Protection Status

Examples of how to replace an existing image in a HTML page using javascript ?

Note: see also How to add an image in a HTML page using javascript ?

Replace an existing image using javscript

Let's consider the following folder with a HTML page (called test.html here) and two images: (that can be found here eiffel-tower.jpeg and eiffel-tower-fliped-vertically.jpeg:

test.html
eiffel-tower-fliped-vertically.jpeg
eiffel-tower.jpeg

the html page shows the image eiffel-tower-fliped-vertically.jpeg:

<!DOCTYPE html>
<html lang="en">

<head>

<title>Test</title>

</head>

<body>

<img src="eiffel-tower-fliped-vertically.jpeg" style="height:700px">

</body>
</html>

How to replace an existing image in a HTML page using javascript ?
How to replace an existing image in a HTML page using javascript ?

to replace the image eiffel-tower-fliped-vertically.jpeg with eiffel-tower.jpeg using javascript:

<!DOCTYPE html>
<html lang="en">

<head>

<title>Test</title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

</head>

<body>

<img id="my_image" src="eiffel-tower-fliped-vertically.jpeg" style="height:700px">

<script>

$("#my_image").attr("src","eiffel-tower.jpeg");

</script>


</body>
</html>

How to replace an existing image in a HTML page using javascript ?
How to replace an existing image in a HTML page using javascript ?

Another example

<!DOCTYPE html>
<html lang="en">

<head>

<title>Test</title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

</head>

<body>

<img id="my_image" src="eiffel-tower-fliped-vertically.jpeg" style="height:700px">


<a href='#' onClick="switch_image_function()">switch picture</a>

<script>

function switch_image_function(image_url) {

        $("#my_image").attr("src","eiffel-tower.jpeg");

}

</script>


</body>
</html>

How to replace an existing image in a HTML page using javascript ?
How to replace an existing image in a HTML page using javascript ?

Add a timestamp

It is also possible to add a timestamp to indicate at the browser that the image has been updated:

<!DOCTYPE html>
<html lang="en">

<head>

<title>Test</title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

</head>

<body>

<img id="my_image" src="eiffel-tower-fliped-vertically.jpeg" style="height:700px">


<a href='#' onClick="switch_image_function()">switch picture</a>

<script>

function switch_image_function(image_url) {

var timestamp = new Date().getTime();

var queryString = "?t=" + timestamp;

$("#my_image").attr("src","eiffel-tower.jpeg"+queryString)

}

</script>


</body>
</html>

References

Image

of