Home >Web Front-end >JS Tutorial >Detailed explanation of jQuery's remove() method_jquery
Definition and usage of remove() method:
This method will remove all matching elements from the DOM.
Note: The remove() method will not delete the matching elements from the jQuery object, so these matching elements can be used again in the future. However, in addition to the element itself being retained, other events such as bound events, Additional data, etc. will be removed.
Grammar structure:
$(selector).remove(expr)
Parameter list:
Parameter Description
expr is optional. jQuery expression for filtering elements
Example code:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("div").remove("#first"); }) }) </script> </head> <body> <div id="first">我是第一</div> <div id="second">我是第二</div> <button>点击</button> </body> </html>
The following code can delete the div with id first in the div collection.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#btd").click(function(){ $("div").remove(); }) }) </script> </head> <body> <div id="first">我是第一</div> <div id="second">我是第二</div> <button id="btd">点击删除第一个div</button> </body> </html>
If the parameter is omitted, all matching elements will be deleted.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style type="text/css"> div{ width:200px; height:200px; border:5px solid green; } </style> <script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#btd").click(function(){ var a=$("div"); a.remove("#first"); $("#btn").click(function(){ alert(a.length); }) }) }) </script> </head> <body> <div id="first">我是第一</div> <div id="second">我是第二</div> <button id="btd">删除第一个div</button><button id="btn">查看删除操作后div的数量</button> </body> </html>
remove() has removed the matching element in the DOM, but it has not removed it from the jquery object.
jquery uses the remove() method to delete child elements of a specified class
<!DOCTYPE html> <html> <head> <script src="js/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").remove(".italic"); }); }); </script> </head> <body> <p>This is a paragraph in the div.</p> <p class="italic"><i>This is another paragraph in the div.</i></p> <p class="italic"><i>This is another paragraph in the div.</i></p> <button>Remove all p elements with class="italic"</button> </body> </html>
After seeing this code, I don’t think I need to explain too much. Everyone will understand, it’s a very interesting method.