change image src with js code example

Example 1: javascript change image src

//change image src
document.getElementById('myImageID').src="images/my_other_image.png";

Example 2: javascript set image src

// Pure JavaScript to Create img tag and add attributes manually ,
var image = document.createElement("img");
var imageParent = document.getElementById("body");
image.id = "id";
image.className = "class";
image.src = searchPic.src;            // image.src = "IMAGE URL/PATH"
imageParent.appendChild(image);

// Set src in pic1
document["#pic1"].src = searchPic.src;

// or with getElementById

document.getElementById("pic1").src= searchPic.src;

// jQuery to archive this,
$("#pic1").attr("src", searchPic.src);

Example 3: js code to change a immage

<script type="text/javascript">
    function changeImage(a) {
        document.getElementById("img").src=a.src;
    }
</script>
<div id="main_img">
    <img id="img" src="1772031_29_b.jpg">
</div>
<div id="thumb_img">
    <img src='1772031_29_t.jpg'  onclick='changeImage("1772031_29_b.jpg");'>
    <img src='1772031_55_t.jpg'  onclick='changeImage("1772031_55_b.jpg");'>
    <img src='1772031_53_t.jpg'  onclick='changeImage("1772031_53_b.jpg");'>
</div>

Tags:

Html Example