Is there a way to overwrite an image already existing in my site using javascript... if yes, what method, and any links for tutorials?
Asked
Active
Viewed 1,330 times
-4
-
1can you explain what you are attempting to accomplish? – Daniel A. White Sep 22 '15 at 12:25
-
Do you want to change src of an image? if yes than ```document.getElementById('myImageId').src = 'new-image.png'``` – Sergiy Kozachenko Sep 22 '15 at 12:28
-
1@Grievoushead there is no suggestion of using jQuery. Good call on posting as a comment because FYI if you post jQuery answers to Javascript questions you often get downvoted. – Popnoodles Sep 22 '15 at 12:28
-
Andrew can you clarify whether you want to do this on the web page or the server? – Popnoodles Sep 22 '15 at 12:29
3 Answers
1
This is a code example in Js :
<script language="javascript">
function ChangeImageSrc(oldSrc, newSrc) {
var imgElements = document.getElementsByTagName('img');
for (i = 0; i < imgElements.length; i++){
if (imgElements[i].src == oldSrc){
imgElements[i].src = newSrc;
break;
}
}
}
</script>

Akram Rekik
- 67
- 9
1
You only need to change the src attribute of your image, you can do something like this:
<script>
function myFunction() {
var x = document.getElementById("myImg").src = 'image2.jpg';
}
</script>
<img src="image1.jpg" id="myImg">
<button onclick="myFunction()">Change Image </button>

Luis
- 56
- 4
0
You can't do this with javascript alone - you will need to have something on your server to actually handle the saving of the image. If you want to overwrite an image, you would simply need to provide the same filename when saving and apply the appropriate permissions.
There are lots of resources available for file/image uploads, eg:
https://joelvardy.com/writing/javascript-image-upload
https://css-tricks.com/ajax-image-uploading/
The right solution for you depends on what you have available on your server.

duncanhall
- 11,035
- 5
- 54
- 86