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";
}
Give your img tag an id, then you can
In this case, as you want to change the
src
of the first value of your element, you have no need to build up a function. You can change this right in the element:You have several ways to do this. You can also create a function to automatize the process:
Then you can:
You can use both jquery and javascript method: if you have two images for example:
1)Jquery Method->
2)Javascript Method->
For this type of issue jquery is the simple one to use.
its ok now
With the snippet you provided (and without making assumptions about the parents of the element) you could get a reference to the image with
and change the src with
so you could achieve the desired effect with
otherwise, as other suggested, if you're in control of the code, it's better to assign an
id
to the image a get a reference withgetElementById
(since it's the fastest method to retrieve an element)