Method: 1. Use the remove() method to remove elements. This method is used to delete specified elements. The syntax is "element object.remove();"; 2. Use the empty() method to remove elements. The method is used to delete all child elements of the specified element. The syntax is "element object.empty();".
The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.
You can delete selected elements and sub-elements through jquery's remove() and empty() methods,
remove() ,
empty() only deletes the child elements of the selected element,
Let’s take a look at them separately:
1. Use the remove method
remove() method to remove the selected element, including all text and child nodes.
This method will also remove the data and events of the selected element.
The syntax is:
$(selector).remove()
The example is as follows:
<html> <head> <meta charset="utf-8"> <title>123</title> <script src="js/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").remove(); }); }); </script> </head> <body> <p>这是一个段落。</p> <p>这是另一个段落。</p> <button>移除所有P元素</button> </body> </html>
Output result:
2. Use the empty method
empty() method to remove all child nodes and content of the selected element.
Note: This method does not remove the element itself, or its attributes.
The syntax is:
$(selector).empty()
The example is as follows:
<html> <head> <meta charset="utf-8"> <title>123</title> <script src="js/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("div").empty(); }); }); </script> </head> <body> <div style="height:100px;background-color:yellow"> 这是一些文本。 <p>这是div块中的一个段落。</p> </div> <p>这是div块外部的一个段落。</p> <button>移除div块中的内容</button> </body> </html>
Output result:
Related video tutorials Recommended: jQuery video tutorial
The above is the detailed content of How to remove elements in jquery. For more information, please follow other related articles on the PHP Chinese website!