Basic usage of empty() for DOM node deletion
Removing nodes on the page is a common operation for developers. jQuery provides several different methods to deal with this problem. Here we take a closer look at the empty method
empty As the name suggests, the empty method. But it is a little different from deletion, because it only removes all child nodes in the specified element.
This method not only removes child elements (and other descendant elements), but also removes the text within the element. Because, according to the description, any text string in an element is regarded as a child node of the element.
Let’s write an example analysis:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title></title> <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script> <style> div { background: #bbffaa; width: 300px; } </style> </head> <body> <div id="div"> <p>p元素1</p> <p>p元素2</p> </div> <button>點(diǎn)擊通過jQuery的empty移除元素</button> <script type="text/javascript"> $("button").on('click', function() { //通過empty移除了當(dāng)前div元素下的所有p元素 //但是本身id=test的div元素沒有被刪除 $("#div").empty() }) </script> </body> </html>
Use a browser to open and run this code, press F12 You can see that the following <div id="div">< ;/div>not deleted