Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically change the src of an img tag

People also ask

How can I change the IMG src?

To change the source or src of an image, you need to add an id or class to the image tag. You can get the image element using the name of the id or class , and you can change the source or src of the image using the src property.

Can JavaScript change the src attribute value of an IMG tag?

The src property sets or returns the value of the src attribute of an image. The required src attribute specifies the URL of an image. Note: The src property can be changed at any time.

Can we change image src using JavaScript?

You can change an HTML image src attribute programatically by using JavaScript. First, you need to grab the HTML element by using JavaScript element selector methods like getElementById() or querySelector() and assign the element to a variable.

What does img src => do?

The img src stands for image source, which is used to specify the source of an image in the HTML <img> tag.


Give your img tag an id, then you can

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

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.


if you use the JQuery library use this instruction:

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

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 image an id. Then you can do this in your javascript.

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

You can use this syntax to change the value of any attribute of any element.