Image Replacement with jQuery

User
div has image replace it with jquery
Assistant
To replace the image inside a “ with another image using jQuery, you can use the following code:

### Example
HTML:

<div id="image-container">
    <img src="old-image.jpg" alt="Old Image" />
</div>

jQuery:

$(document).ready(function () {
    // Replace the image
    $('#image-container img').attr('src', 'new-image.jpg').attr('alt', 'New Image');
});

### Explanation:
1. **Select the Image:** The selector `$('#image-container img')` targets the “ element inside the “ with `id="image-container"`.
2. **Replace Attributes:** The `attr` method changes the `src` and `alt` attributes of the image.

### If the Image Needs to Be Completely Replaced
If you want to remove the old “ tag and insert a new one:

$(document).ready(function () {
    // Completely replace the image
    $('#image-container').html('<img src="new-image.jpg" alt="New Image" />');
});

This approach removes the existing “ tag and adds a new one with the specified `src` and `alt` attributes.

Leave a Comment

Your email address will not be published. Required fields are marked *