jQuery replaceWithメソッドで指定要素を置き換えるサンプル
環境
jQuery 3.6.0
Windows 10 Home 64bit
構文
$(置換対象セレクター名).replaceWith(置換後の要素)
replaceWithは、要素を置換えます。
$()はjQueryオブジェクトです。
replaceAllとの違いは、置換対象と置換後の要素が逆です。
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
$("#btnchg").click(function() {
//replaceWithメソッドでspan要素を置換
$("#show").replaceWith('<span id="show">大阪</span>');
});
});
</script>
</head>
<body>
<p>都市:<span id = "show">東京</span></p>
<input type="button" id="btnchg" value="変更">
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
$("#btnchg").click(function() {
//replaceWithメソッドでspan要素を置換
$("#show").replaceWith('<span id="show">大阪</span>');
});
});
</script>
</head>
<body>
<p>都市:<span id = "show">東京</span></p>
<input type="button" id="btnchg" value="変更">
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(function(){ $("#btnchg").click(function() { //replaceWithメソッドでspan要素を置換 $("#show").replaceWith('<span id="show">大阪</span>'); }); }); </script> </head> <body> <p>都市:<span id = "show">東京</span></p> <input type="button" id="btnchg" value="変更"> </body> </html>
実行結果
「変更」ボタンを押すと、文字が「東京」から「大阪」に変わります。