There are three ways to delete elements and content in jQuery, namely: remove() method, detach() method and empty() method. The following article will introduce to you how these three methods delete elements, and what are the differences between the remove() method, the detach() method and the empty() method. [Video tutorial recommendation: jQuery tutorial]
jQuery remove() method
remove () method is used to delete the selected element, including all text and child node elements within it.
The following is a code example to learn how the remove() method deletes elements.
<!DOCTYPE html> <html> <meta charset="UTF-8"> <head> <title>jQuery remove()方法</title> <style> #demo{ padding: 10px; border: 1px solid red; } </style> </head> <body> <h1 style="color:red;">PHP中文网</h1> <div id="demo"> <h2>使用remove()方法删除!</h2> <p>测试文本!</p> </div> <br> <button>删除</button> <script src="js/jquery.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("#demo").remove(); }); }); </script> </body> </html>
Output:
Before clicking the delete button:
##After clicking the delete button:
jQuery detach() method
The detach() method is used to delete the selected element, including all text and child node elements within it.<script src="js/jquery.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("#demo").detach(); }); }); </script>
##After clicking the delete button:
Explanation: The remove() and detach() methods both delete the selected element and all the contents inside it, but The remove() method will only retain the element itself, but not the jQuery data of the element. For example, bound events and data will be removed.
However, in addition to retaining the element itself, the detach() method will also retain all bound events, additional data, etc.
jQuery empty() methodThe empty() method is used to remove all content contained in the selected element, including all text. and child elements.
The following is a code example to learn how the empty() method deletes elements.
<script src="js/jquery.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("#demo").empty(); }); }); </script>
Output:
Before clicking the delete button:
##After clicking the delete button:
Note: The
empty() method will only delete all content within the selected element, but the selected element itself will not be deleted.
The above is the entire content of this article, I hope it will be helpful to everyone's study. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !The above is the detailed content of How to delete elements with jQuery? Simple comparison of remove(), detach() and empty(). For more information, please follow other related articles on the PHP Chinese website!