Home >Web Front-end >Front-end Q&A >How to delete an element object in jquery
Jquery method to delete an element object: 1. Use "$(selector)" to obtain the element object of the specified element; 2. Use the remove() method or detach() method to delete the obtained specified element object. Yes, the syntax is "element object.remove()" and "element object.detach()".
The operating environment of this tutorial: windows10 system, jquery3.6.0 version, Dell G3 computer.
1. Get the element object of the specified element
The syntax is:
$(selector)
2. Delete element object
(1) The remove() method removes 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()
(2) The detach() method removes the selected elements, including all text and child nodes. It then persists the data and events.
This method keeps a copy of the removed elements, allowing them to be reinserted later.
The syntax is:
$(selector).detach()
The example is as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>123</title> <script src="js/jquery.min.js"> </script> <script> $(document).ready(function(){ $(".bt1").click(function(){ $(".p1").remove(); }); $(".bt2").click(function(){ $(".p2").detach(); }); }); </script> </head> <body> <p class="p1">这是一个段落。</p> <p class="p2">这是另一个段落。</p> <button class="bt1">remove移除P元素</button> <button class="bt2">detach移除P元素</button> </body> </html>
Output result:
Video tutorial recommendation :jQuery video tutorial
The above is the detailed content of How to delete an element object in jquery. For more information, please follow other related articles on the PHP Chinese website!