Is there a way to change an source’s extension explicitly using JS?

Beginner here. I have a series of HTML IMG elements that look like this:

<img src="1.png" onclick="changeImg(this)">
<img src="2.png" onclick="changeImg(this)">
<img src="3.png" onclick="changeImg(this)">

What I would like the “changeImg” JS function to do is, on click, change the image source from “1.png” to “1.gif”. Essentially, just changing the last 3 letters of the img source.

The purpose of this is to allow users to click on an element in order to play an animated GIF. As such, “1.png” is simply a static PNG version of the animated “1.gif”. Can this be done?


Use img.src:

function changeImg(img) {
  img.src = img.src.replace('png', 'gif');
<img src="1.png" onclick="changeImg(this)">