jQuery Method How to - Use empty() to remove all child nodes (including text nodes) from all paragraphs








Question

We would like to know how to use empty() to remove all child nodes (including text nodes) from all paragraphs.

Answer


<!--from w w  w  . ja  va 2  s  .  c  om-->
<html>
  <head>
    <script type="text/javascript" src='http://code.jquery.com/jquery-1.5.2.js'></script>
    <script type="text/javascript">
        $(document).ready(function(){
                  $("p").click(function () {
                      $(this).empty();
                  });
        });
    </script>
  </head>
  <body>
            <p>World</p>
            <div>Replaced!</div>
  </body>
</html>

The code above is rendered as follows: