jQuery 2種 置換元素(replaceWith、replaceAll)

將現存的元素置換成另一種元素

.replaceWith()

1
2
3
$(function() {
$('h2').replaceWith('<div>水餃_N</div>');
})
1
2
3
4
5
<!-- 執行前 -->
<h2>蛋糕</h2>

<!-- 執行後 -->
<div>水餃_N</div>

.replaceAll()

與 .replaceWith() 類似,差別在物件與參數關係顛倒。可和 jQuery 動態插入元素 (before、after、prepend、append)視為一樣的關係

1
2
3
$(function() {
$('<div>水餃_N</div>').replaceAll('h2');
})
1
2
3
4
5
<!-- 執行前 -->
<h2>蛋糕</h2>

<!-- 執行後 -->
<div>水餃_N</div>