- jQuery 教程
- jQuery - 首頁
- jQuery - 路線圖
- jQuery - 概述
- jQuery - 基礎
- jQuery - 語法
- jQuery - 選擇器
- jQuery - 事件
- jQuery - 屬性
- jQuery - AJAX
- jQuery DOM 操作
- jQuery - DOM
- jQuery - 新增元素
- jQuery - 刪除元素
- jQuery - 替換元素
- jQuery CSS 操作
- jQuery - CSS 類
- jQuery - 尺寸
- jQuery - CSS 屬性
- jQuery 效果
- jQuery - 效果
- jQuery - 動畫
- jQuery - 鏈式操作
- jQuery - 回撥函式
- jQuery 遍歷
- jQuery - 遍歷
- jQuery - 遍歷祖先元素
- jQuery - 遍歷子孫元素
- jQuery UI
- jQuery - 互動
- jQuery - 小部件
- jQuery - 主題
- jQuery 參考
- jQuery - 選擇器
- jQuery - 事件
- jQuery - 效果
- jQuery - HTML/CSS
- jQuery - 遍歷
- jQuery - 雜項
- jQuery - 屬性
- jQuery - 實用工具
- jQuery 外掛
- jQuery - 外掛
- jQuery - PagePiling.js
- jQuery - Flickerplate.js
- jQuery - Multiscroll.js
- jQuery - Slidebar.js
- jQuery - Rowgrid.js
- jQuery - Alertify.js
- jQuery - Progressbar.js
- jQuery - Slideshow.js
- jQuery - Drawsvg.js
- jQuery - Tagsort.js
- jQuery - LogosDistort.js
- jQuery - Filer.js
- jQuery - Whatsnearby.js
- jQuery - Checkout.js
- jQuery - Blockrain.js
- jQuery - Producttour.js
- jQuery - Megadropdown.js
- jQuery - Weather.js
- jQuery 有用資源
- jQuery - 問答
- jQuery - 快速指南
- jQuery - 有用資源
- jQuery - 討論
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 參考。
廣告
