jQuery empty()

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

jQuery empty()

The jQuery empty() method is used to remove all child nodes and content from the selected elements. This method doesn't remove the element itself.

If you want to remove the element without removing data and events, you should use the detach() method.

If you want to remove the element as well as its data and events, you should use the remove() method.

Syntax:

  1. $(selector).empty()  

Example of jQuery empty() method

Let's take an example to demonstrate the jQuery empty() method.

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  
  5. <script>  
  6. $(document).ready(function(){  
  7.     $("button").click(function(){  
  8.         $("div").empty();  
  9.     });  
  10. });  
  11. </script>  
  12. </head>  
  13. <body>  
  14. <div style="height:150px;background-color:yellow">  
  15. Twinkle, twinkle, little star,<br/>  
  16. How I wonder what you are!</br>  
  17. Up above the world so high,<br/>  
  18. Like a diamond in the sky.<br/>  
  19. Twinkle, twinkle, little star,<br/>  
  20. How I wonder what you are!<br/>  
  21. <p><b>This poem is written inside the div.</b></p>  
  22. </div>  
  23. <p>This paragraph is written outside the div.</p>  
  24. <button>Execute empty() method to remove the content of div element.</button>  
  25. </body>  
  26. </html>  

Test it Now

jQuery empty() example 2

  1. <!DOCTYPE html>  
  2. <html>  
  3.    <head>  
  4.       <title>The jQuery Example</title>  
  5.       <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>  
  6. <script type="text/javascript" language="javascript">  
  7.       $(document).ready(function() {  
  8.          $("div").click(function () {  
  9.             $(this).empty();  
  10.          });  
  11.       });  
  12. </script>  
  13. <style>  
  14. .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}  
  15. </style>  
  16. </head>  
  17. <body>  
  18. <p>Click any of the box given below to see the result:</p>  
  19. <div class="div" style="background-color:yellow;">Click me!</div>  
  20. <div class="div" style="background-color:green;">Click me!</div>  
  21. <div class="div" style="background-color:red;">Click me!</div>  
  22. </body>  
  23. </html>  

Test it Now