Home > Article > Web Front-end > How to delete all child elements in div with jquery
Deletion method: 1. Use empty(), the syntax "$("div").empty();" to delete all child nodes and content; 2. Use children() and remove(), The syntax "$("div").children().remove();" only deletes the child elements but not the content.
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
jquery deletes all child elements within the div
Method 1: Use empty()
The empty() method removes all child nodes and content of the selected element. This method does not remove the element itself, or its attributes.
The empty() method is used to "empty" descendant elements.
<!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() { $("div").empty(); }); }); </script> </head> <body> <div style="height:100px;background-color:yellow"> 这是一些文本。 <p>这是div块中的一个段落。</p> </div> <p>这是div块外部的一个段落。</p> <button>移除div块中的内容</button> </body> </html>
Method 2: Use children() and remove()
remove( ) method can remove elements and their internal Deletion of all content
Therefore, you need to first use the children() method to obtain all child elements of the div element, and then use the remove() method to delete the obtained child elements.
But this method will not delete the text content of the div element itself.
<!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() { $("div").children().remove(); }); }); </script> </head> <body> <div style="height:100px;background-color:yellow"> 这是一些文本。 <p>这是div块中的一个段落,子元素。</p> <p>这是div块中的一个段落,子元素。</p> </div> <p>这是div块外部的一个段落。</p> <button>移除div块中的内容</button> </body> </html>
[Recommended learning: jQuery video tutorial, web front-end video】
The above is the detailed content of How to delete all child elements in div with jquery. For more information, please follow other related articles on the PHP Chinese website!