Programmatically change the src of an img tag

Jam Ville picture Jam Ville · Jul 30, 2012 · Viewed 732.8k times · Source

How can I change the src attribute of an img tag using javascript?

<img src="../template/edit.png" name=edit-save/>

at first I have a default src which is "../template/edit.png" and I wanted to change it with "../template/save.png" onclick.

UPDATED: here's my html onclick:

<a href='#' onclick='edit()'><img src="../template/edit.png" id="edit-save"/></a>

and my JS

function edit()
{   
    var inputs = document.myform;
    for(var i = 0; i < inputs.length; i++) {
        inputs[i].disabled = false;
    }
}

I've tried inserting this inside the edit(), it works but need to click the image twice

var edit_save = document.getElementById("edit-save");
    edit_save.onclick = function(){
       this.src = "../template/save.png";
    }

Answer

Matthias picture Matthias · Jul 30, 2012

Give your img tag an id, then you can

document.getElementById("imageid").src="../template/save.png";