The difference between jQuery DOM operation empty and remove
When you want to remove specified elements, jQuery provides two methods, empty() and remove([expr]). Both of them delete elements, but there are still differences between them.
empty Method
Strictly speaking, the empty() method does not delete the node, but clears the node. It can clear all descendant nodes in the element
Strictly speaking, empty cannot delete its own node
remove method
This node and all descendant nodes contained in this node will be deleted at the same time
Provides a filtering expression to be passed to delete elements in the specified collection
Below we will use code to analyze in detail
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>remove()与empty()的区别</title> <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script> <style type="text/css"> #dv1{ width:250px; height:250px; background:red; float:left; } #dv2{ width:250px; height:250px; background:green; float: left; margin-left:5px; margin-right:5px; } </style> </head> <body> <div id="dv1"> <p>元素1</p> <p>元素2</p> </div> <div id="dv2"> <p>元素3</p> <p>元素4</p> </div> <input type="button" value="empty" id="but1"> <input type="button" value="remove" id="but2"> <script> $("#but1").click(function(){ $("#dv1").empty(); }) $("#but2").click(function(){ $("#dv2").remove(); }) </script> </body> </html>
The above code, after we run it, we can see that when I click empty, element 1 and element 2 will be cleared, but the div still exists ’
When I click remove, not only the elements inside will be deleted, but also the div itself will be deleted