JavaScript Program to Delete an Image by Clicking on a Button
Last Updated :
25 Oct, 2023
In this article, we will learn how to delete an image by clicking on a button in JavaScript. In web development, there are scenarios where you may want to provide users with the ability to delete an image by clicking on a button. This can be useful in various applications, such as image galleries or user profile settings.
Approach
The approach to deleting an image by clicking on a button is by using HTML DOM methods. It will be done as:
Example 1: In this method, we will directly manipulate the DOM to remove the image element when the user clicks the delete button using the HTML removeChild method.
HTML
<!DOCTYPE html>
< html >
< head >
< title >
Delete Image on Button Click
</ title >
</ head >
< body >
< img id = "imageElement"
src =
alt = "Image 1" >
< button id = "deleteButton" >
Delete Image
</ button >
< script >
const deleteButton = document
.getElementById('deleteButton');
const imageElement = document
.getElementById('imageElement');
deleteButton.addEventListener('click',
function () {
imageElement.parentNode.removeChild(imageElement);
});
</ script >
</ body >
</ html >
|
Output:
Example 2: In this examle, we use event delegation to handle the click event on the parent container of the images. This is useful when dealing with multiple images and delete buttons.
HTML
<!DOCTYPE html>
< html >
< head >
< title >
Delete Image on Button Click
</ title >
</ head >
< body >
< div id = "imageContainer" >
< img src =
alt = "Image 1" >
< button class = "deleteButton" >
Delete Image
</ button >
< img src =
alt = "Image 2" >
< button class = "deleteButton" >
Delete Image
</ button >
</ div >
< script >
const imageContainer = document
.getElementById('imageContainer');
imageContainer.addEventListener('click',
function (event) {
if (event.target.classList.contains('deleteButton')) {
const imageElement =
event.target.previousElementSibling;
imageElement.parentNode.removeChild(imageElement);
}
});
</ script >
</ body >
</ html >
|
Output:
Share your thoughts in the comments
Please Login to comment...