📜  jquery on click remove parent div - Javascript(1)

📅  最后修改于: 2023-12-03 15:16:43.900000             🧑  作者: Mango

jQuery on click remove parent div - Javascript

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.

Prerequisites

Basic knowledge of HTML, CSS, and JavaScript is assumed.

Instructions
  1. 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>
    
  2. 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".

  3. 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.

  4. 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.

Conclusion

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.