【replaceWith】jQueryでタグの要素をすべて変更する

特定のタグやクラス名を変更させたいときにjQueryのreplaceWithを使うことで実現できます。

replaceWithは、指定する特定の要素やクラス名の要素を変更させることができます。

replaceWithの使い方

要素とテキストを変更する

下のサンプルは<span>変更前のテキスト</span>をpタグに変更し、タグとテキストを変更する方法になります。

html

<span>変更前のテキスト</span>

jQuery

jQuery('span').replaceWith('<p>spanタグからpタグに変更しました</p>');

テキストは変えずに要素を変える方法

次はテキストの内容を変えずにタグのみを変更させる方法になります。

html

<p>pタグの要素</p>

jQuery

jQuery('p').replaceWith(function() {
	var text = jQuery(this).text();
	jQuery(this).replaceWith( "<div>" + text + "</div>" );
});

replaceAll

replaceWithに似たものにreplaceAllがあります。

二つの違いはオブジェクトと引数の位置が逆になります。

replaceWith

replaceWithの書き方
$(置換させる要素).replaceWith(置き換え後の要素を指定);

replaceAll

replaceAllの書き方
$(置き換え後の要素を指定).replaceAll(置換させる要素)

replaceWithのサンプル

コメント

タイトルとURLをコピーしました