「jQuery」.replaceWithで指定要素を別の要素に置き換える

2022年2月18日

書式
$(セレクタ名).replaceWith(置き換える要素)
.replaceWith() を使用して指定した要素を別の要素に置き換えります。
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!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>
<!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>
<!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」に変わります。

jQuery

Posted by arkgame