「jQuery」.replaceWithで指定要素を別の要素に置き換える
書式
$(セレクタ名).replaceWith(置き換える要素)
.replaceWith() を使用して指定した要素を別の要素に置き換えります。
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
//ボタンを押すと、テキストボックスをspanタグに変更
$('#btnChange').click(function(){
$('#username').replaceWith("<span style='color:skyblue;'>" + $('#username').val() + "</span>");
});
});
</script>
</head>
<body>
<p>
<input type="text" id="username" value="山田">
</p>
<p><input type="button" id="btnChange" value="検証"></p>
</body>
</html>
結果
「検証」ボタンを押すと、テキストボックスをspanタグに変更します、文字の色は「skyblue」に変わります。