jQuery - 替換元素



jQuery 提供了 **replaceWith()** 方法,用於在給定的 HTML 文件中用新內容替換現有的 HTML 內容。

jQuery replaceWith() 方法

jQuery 的 **replaceWith()** 方法會從 DOM 中移除內容,並在其位置插入新內容。

以下是 **replaceWith()** 方法的語法

$(selector).replaceWith(newContent);
replaceWith() 方法會移除與已移除節點關聯的所有資料和事件處理程式。

概述

考慮以下 HTML 內容

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

現在,如果我們如下應用 **replaceWith()** 方法

$( ".hello" ).replaceWith("<h2>New Element</h2>" );

它將產生以下結果

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

如果我們在 <div class="hello"> 內部有任何數量的巢狀元素,它們也將被移除。

示例

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

<!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" ).replaceWith("<h2>New Element</h2>" );
      });
   });
</script>
</head>
<body>
   <div class="container">
      <h2>jQuery replaceWith() Method</h2>
      <div class="hello">Hello</div>
      <div class="goodbye">Goodbye</div>
      <div class="hello">Hello</div>
   </div>
   <br>
   
   <button>Replace Element</button>
</body>
</html>

示例

以下示例將所有段落替換為 **Brilliant**。

<!doctype html>
<html lang="en">
<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(){
         $( "p" ).replaceWith( "<b>Brilliant</b>" );
      });
   });
</script>
</head>
<body>
   <h2>jQuery replaceWith() Method</h2>
   <p>Zara</p>
   <p>Nuha</p>
   <p>Ayan</p>
 
   <button>Replace Element</button>
</body>
</html>

jQuery HTML/CSS 參考

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

廣告