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.com/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.com/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 参考

广告

© . All rights reserved.