如何使用 jQuery 從 DOM 中移除一個元素?


empty() 方法從匹配元素的集合中刪除所有子節點,而 remove() 方法從 DOM 中刪除所有匹配元素。

要刪除一個元素,請使用 remove() 方法。

示例

你可以嘗試執行以下程式碼以瞭解如何使用 jQuery 從 DOM 中刪除一個元素

線上演示

<html>
   <head>
      <title>jQuery remove() method</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("div").click(function () {
               $(this).remove( );
            });
         });
      </script>
       
      <style>
         .div {
             margin:10px;
             padding:12px;
             border:2px solid #666;
             width:60px;
         }
      </style>
   </head>
   
   <body>
   
      <p>Click on any square below:</p>
      <span id = "result"> </span>
       
      <div class = "div" style = "background-color:blue;"></div>
      <div class = "div" style = "background-color:green;"></div>
      <div class = "div" style = "background-color:red;"></div>
       
   </body>
</html>

更新於: 2019 年 12 月 17 日

867 次瀏覽

開啟你的事業

完成課程後獲得認證

開始
廣告
© . All rights reserved.