To replace an image in HTML using JavaScript, you can use the DOM manipulation methods provided by JavaScript. Here's a step-by-step guide on how to achieve this:


<!DOCTYPE html> <html> <head> <title>Replace Image using JavaScript</title> </head> <body> <img id="myImage" src="old_image.jpg" alt="Old Image"> <button onclick="replaceImage()">Replace Image</button> <script src="script.js"></script> </body> </html>

JavaScript (script.js):

function replaceImage() { // Get the reference to the image element var imageElement = document.getElementById('myImage'); // Create a new image element var newImageElement = document.createElement('img'); // Set attributes for the new image newImageElement.src = 'new_image.jpg'; newImageElement.alt = 'New Image'; // Replace the old image with the new one imageElement.parentNode.replaceChild(newImageElement, imageElement); }

In this example, we have an HTML page with an image (myImage) and a button. When the button is clicked, the replaceImage() function is called, which does the following:

  1. Fetch the reference to the existing image element using document.getElementById.
  2. Create a new image element using document.createElement.
  3. Set the src and alt attributes for the new image element.
  4. Replace the old image element with the new one using parentNode.replaceChild.

Upon clicking the "Replace Image" button, the old image with the ID "myImage" will be replaced with the new image specified by the src attribute in the JavaScript function.

Remember to adjust the image filenames and attributes as per your requirements. Additionally, you can apply CSS styles to the image elements to control their appearance, size, and positioning.

Have questions or queries?
Get in Touch