[javascript] Programmatically change the src of an img tag

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";
    }

This question is related to javascript html image src

The answer is


its ok now

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

    var edit_save = document.getElementById("edit-save");

       edit_save.src = "../template/save.png";                              
}

Give your img tag an id, then you can

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

Give your image an id. Then you can do this in your javascript.

document.getElementById("blaah").src="blaah";

You can use the ".___" method to change the value of any attribute of any element.


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

if you use the JQuery library use this instruction:

$("#imageID").attr('src', 'srcImage.jpg');

With the snippet you provided (and without making assumptions about the parents of the element) you could get a reference to the image with

document.querySelector('img[name="edit-save"]');

and change the src with

document.querySelector('img[name="edit-save"]').src = "..."

so you could achieve the desired effect with

var img = document.querySelector('img[name="edit-save"]');
img.onclick = function() {
    this.src = "..." // this is the reference to the image itself
};

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 with getElementById (since it's the fastest method to retrieve an element)


You can use both jquery and javascript method: if you have two images for example:

<img class="image1" src="image1.jpg" alt="image">
<img class="image2" src="image2.jpg" alt="image">

1)Jquery Method->

$(".image2").attr("src","image1.jpg");

2)Javascript Method->

var image = document.getElementsByClassName("image2");
image.src = "image1.jpg"

For this type of issue jquery is the simple one to use.


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:

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

You have several ways to do this. You can also create a function to automatize the process:

function changeSrc(p, t) { /* where p: Parent, t: ToSource */
  p.firstChild.src = t
}

Then you can:

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

Maybe because you have a tag like a parent of the tag. That why you have to click two time the images.

For me the solution is this: http://www.w3schools.com/js/tryit.asp?filename=tryjs_intro_lightbulb


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to image

Reading images in python Numpy Resize/Rescale Image Convert np.array of type float64 to type uint8 scaling values Extract a page from a pdf as a jpeg How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? Angular 4 img src is not found How to make a movie out of images in python Load local images in React.js How to install "ifconfig" command in my ubuntu docker image? How do I display local image in markdown?

Examples related to src

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this? Angular 4 img src is not found Rotate an image in image source in html html script src="" triggering redirection with button What is the right way to write my script 'src' url for a local development environment? How to properly reference local resources in HTML? Dynamically add script tag with src that may include document.write Programmatically change the src of an img tag Get img src with PHP Javascript : get <img> src and set as variable?