📅  最后修改于: 2023-12-03 15:16:43.900000             🧑  作者: Mango
When working with the HTML DOM, it is sometimes necessary to remove elements from the page. In this article, we will discuss how to use jQuery to remove a parent div on click.
Basic knowledge of HTML, CSS, and JavaScript is assumed.
Add jQuery to your project. You can either download the latest version from jquery.com or use a Content Delivery Network (CDN), like so:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
Create an HTML document with a div element and a button:
<div class="parent">
<p>Hello World!</p>
<button class="child">Remove Parent</button>
</div>
In this example, the parent div has a class of "parent" and contains a child button with a class of "child".
Add the following JavaScript code to your project:
$(document).ready(function() {
$('.child').click(function() {
$(this).parent().remove();
});
});
This code attaches a click event listener to the child button. When the button is clicked, it finds the parent element of the button (in this case, the parent div) and removes it from the page.
Test your code by opening the HTML document in a web browser and clicking the "Remove Parent" button. The parent div should be removed from the page.
Using jQuery, it is easy to remove elements from the page. By attaching a click event listener to a child element and using the .parent() and .remove() methods, you can remove the parent element of the child with just a few lines of code.