jQuery - 刪除元素



jQuery 提供了 `remove()` 和 `empty()` 方法來從 HTML 文件中刪除現有的 HTML 元素。

jQuery remove() 方法

jQuery 的 `remove()` 方法刪除選定的元素及其子元素。

`remove()` 方法的語法如下:

$(selector).remove();

當您想要刪除元素本身及其內部所有內容時,應該使用 `remove()` 方法。

摘要

考慮以下 HTML 內容:

<div class="container">
   <h2>jQuery remove() Method</h2>
   <div class="hello">Hello</div>
   <div class="goodbye">Goodbye</div>
</div>

如果我們應用 `remove()` 方法如下:

$( ".hello" ).remove();

它將產生以下結果:

<div class="container">
   <h2>jQuery remove() Method</h2>
   <div class="goodbye">Goodbye</div>
</div>

如果 `

` 內有任何數量的巢狀元素,它們也將被刪除。

示例

讓我們嘗試以下示例並驗證結果:

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://tutorialspoint.tw/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("button").click(function(){
         $( ".hello" ).remove();
      });
   });
</script>
</head>
<body>
   <div class="container">
      <h2>jQuery remove() Method</h2>
      <div class="hello">Hello</div>
      <div class="goodbye">Goodbye</div>
   </div>
   <br>
   
   <button>Remove Text</button>
</body>
</html>

帶過濾器的刪除

我們還可以將選擇器作為可選引數包含在 `remove()` 方法中。例如,我們可以將之前的 DOM 刪除程式碼改寫為:

讓我們嘗試以下示例並驗證結果:

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://tutorialspoint.tw/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("button").click(function(){
         $("div").remove(".hello");
      });
   });
</script>
</head>
<body>
   <div class="container">
      <h2>jQuery remove(selector) Method</h2>
      <div class="hello">Hello</div>
      <div class="goodbye">Goodbye</div>
   </div>
   <br>
   
   <button>Remove Text</button>
</body>
</html>

jQuery empty() 方法

jQuery 的 `empty()` 方法與 `remove()` 非常相似,它從文件中刪除選定的元素及其子元素。此方法不接受任何引數。

`empty()` 方法的語法如下:

$(selector).empty();

當您想要刪除元素本身及其內部所有內容時,應該使用 `empty()` 方法。

摘要

考慮以下 HTML 內容:

<div class="container">
   <h2>jQuery empty() Method</h2>
   <div class="hello">Hello</div>
   <div class="goodbye">Goodbye</div>
</div>

如果我們應用 `empty()` 方法如下:

$( ".hello" ).empty();

它將產生以下結果:

<div class="container">
   <h2>jQuery empty() Method</h2>
   <div class="goodbye">Goodbye</div>
</div>

示例

讓我們嘗試以下示例並驗證結果:

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://tutorialspoint.tw/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("button").click(function(){
         $( ".hello" ).empty();
      });
   });
</script>
</head>
<body>
   <div class="container">
      <h2>jQuery empty() Method</h2>
      <div class="hello">Hello</div>
      <div class="goodbye">Goodbye</div>
   </div>
   <br>
   
   <button>Remove Text</button>
</body>
</html>

jQuery HTML/CSS 參考

您可以在以下頁面獲得操作 CSS 和 HTML 內容的所有 jQuery 方法的完整參考:jQuery HTML/CSS 參考

廣告