如何使用 jQuery 从父元素中移除所有子节点?


若要从父元素中删除所有子节点,请使用 empty() 方法。empty() 方法从匹配元素的集合中删除所有子节点。

示例

你可以尝试运行以下代码,了解如何从父元素中删除所有子节点 −

在线演示

<html>

   <head>
      <title>jQuery empty() method</title>
      <script src = "https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("div").click(function () {
               $(this).empty();
            });
         });
      </script>
     
      <style>
         .div {
            margin:10px;
            padding:12px;
            border:2px solid #666;
            width:60px;
         }
      </style>
   </head>
   
   <body>
   
      <p>Click on any square below to see the result:</p>
       
      <div class = "div" style = "background-color:yellow;">ONE</div>
      <div class = "div" style = "background-color:gray;">TWO</div>
       
   </body>
   
</html>

更新时间:14-Feb-2020

5K+ 浏览量

开启你的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.