Home >Web Front-end >Front-end Q&A >How to delete an element in jquery
Methods to delete elements: 1. Use remove() to delete the specified element and all the content inside it. The syntax is "$(selector).remove()"; 2. Use detach() to remove it. Except the selected element and all text and child nodes inside it, the syntax is "$(selector).detach()".
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
Delete an element in jQuery
1. Use the remove() method
in jQuery , we can use the remove() method to delete an element and all its contents.
Syntax:
$(selector).remove()
Example: Use remove() to remove p element
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("p").remove(); }); }); </script> </head> <body> <div>这是一个div段落。</div> <p>这是另一个p段落。</p> <button>移除P元素</button> </body> </html>
2. Use detach() Method
In jQuery, we can use the detach() method to remove selected elements, including all text and child nodes. However it will retain data and events.
This method keeps a copy of the removed elements, allowing them to be reinserted later.
Grammar:
$(selector).detach()
Example: Use detach() to remove the p element
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("p").detach(); }); }); </script> </head> <body> <p>这是另一个p段落。</p> <div>这是一个div段落。</div> <button>移除P元素</button> </body> </html>
[Recommended learning: jQuery video Tutorial、web front-end video】
The above is the detailed content of How to delete an element in jquery. For more information, please follow other related articles on the PHP Chinese website!