jQuery 要素を置き換える(replaceWith/replaceAll)

jQueryの要素を置き換えるサンプルです。

目次 要素を置き換える(replaceWith)
要素を置き換える(replaceAll)

要素を置き換える(replaceWith)

$(置換対象).replaceWith(置換後の要素)
  • replaceWithは、要素を置換えます。
  • replaceAllとの違いは、置換対象と置換後の要素が逆です。
  • $()はjQueryオブジェクトです。
  • 以下はjQueryサイトのreplaceWithメソッドのページです。
    http://api.jquery.com/replacewith/

要素を置き換えるサンプル

ボタン1またはボタン2を押すと、文字が変わります。

テスト:あいうえお

 

上記サンプルのコードです。

<p>テスト:<span id = "span1">あいうえお</span></p>
<input type="button" id="button1" value="ボタン1">
<input type="button" id="button2" value="ボタン2">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>

	$("#button1").click(function() {
		$("#span1").replaceWith('<span id = "span1">かきくけこ</span>');
	});

	$("#button2").click(function() {
		$("#span1").replaceWith('<span id = "span1">さしすせそ</span>');
	});

</script>

9,13行目は、replaceWithメソッドで1行目のspan要素を置換えます。

 

要素を置き換える(replaceAll)

$(置換後の要素).replaceAll(置換対象)
  • replaceAllは、要素を置換えます。
  • replaceWithとの違いは、置換対象と置換後の要素が逆です。
  • $()はjQueryオブジェクトです。
  • 以下はjQueryサイトのreplaceAllメソッドのページです。
    http://api.jquery.com/replaceAll/

要素を置き換えるサンプル

ボタン1またはボタン2を押すと、文字が変わります。

テスト:あいうえお

 

上記サンプルのコードです。

<p>テスト:<span id = "span2">あいうえお</span></p>
<input type="button" id="button3" value="ボタン3">
<input type="button" id="button4" value="ボタン4">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>

	$("#button3").click(function() {
		$('<span id = "span2">かきくけこ</span>').replaceAll('#span2');
	});

	$("#button4").click(function() {
		$('<span id = "span2">さしすせそ</span>').replaceAll('#span2');
	});

</script>

9,13行目は、replaceAllメソッドで1行目のspan要素を置換えます。

関連の記事

jQuery 要素を追加/子要素の先頭最後(append)
jQuery 要素を移動/子要素の先頭最後(appendTo)
jQuery 要素を削除するremoveとemptyの違い

△上に戻る