In the past year, I was searching for the same solution to delete or remove div on button click. I got one of the best solution for this. If you want to delete or remove a div block on the button click then use the jQuery remove() method.
For example, if you want to remove one div only-
<!DOCTYPE html>
<html>
<head>
<title>Remove or delete div on button click using JavaScript jQuery library</title>
</head>
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#remove").click(function(){
$("#msg").remove();
});
});
</script>
<body>
<div id="msg">This is my message content..</div>
<button type="button" id="remove">Remove</button>
</body>
</html>
Execute the above HTML code. You can remove the div block with a button click.
How to remove specific div on button click using JavaScript jQuery?
You can remove specific div rows using the remove() method of jQuery.Suppose that, you fetch data from the database with a table row id number. You can display row numbers with div id using a loop in any programming. If you want to make it dynamically create a JavaScript function with arguments.
For example -
<!DOCTYPE html>
<html>
<head>
<title>Remove specific div row on button click in jQuery</title>
</head>
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<script type="text/javascript">
function deleteRow(rowId)
{
$("#msg_"+rowId).remove();
}
</script>
<body>
<div id="msg_1">This is row 1.. </div>
<button type="button" onClick="deleteRow(1);">Remove</button>
<hr>
<div id="msg_2">This is row 2..</div>
<button type="button" onClick="deleteRow(2);" >Remove</button>
</body>
</html>
In the above example, I created two-row data with HTML div tags and a remove button for each row. As you can check in the above example, I created a deleterow() user-defined function with an argument. If you want to delete a specific row data, you have to create a function with the argument in JavaScript.I created a function inside the script tag with a rowId parameter.
We can concatenate div row id with msg id using the plus sign in JavaScript and use jQuery remove() mehod to create remove or delete operation. Each row will contain a remove button. You can delete specific div data using the near-remove button.