jQuery wrap(unwrap)メソッドで個別に要素で囲む(削除)する

環境
jQuery 3.6.0
Windows 10 Home 64bit

構文
1.$(セレクター名).wrap(要素タグ)
wrapメソッドで個別に引数の要素で囲みます。
2.$(セレクター名).unwrap().text(文字の値);
unwrapメソッドで指定の要素の親の要素を削除します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<style>
.cft{
color:red;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
$("#btnchg").click(function() {
const tArr = $(".ta").text();
if(tArr[0] === "黒" ){
  /*wrapメソッドで個別に引数の要素で囲む*/
$(".ta").wrap("<p class='cft'></p>").text("赤");
}else{
   /*unwrapメソッドで指定の要素を削除*/
$(".ta").unwrap().text("赤");
}
});
});
</script>
</head>
<body>
<div class="ta"></div>
<div class="ta"></div>
<input type="button" id="btnchg" value="変更">
</body>
</html>
<!DOCTYPE html> <html> <head> <style> .cft{ color:red; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(function(){ $("#btnchg").click(function() { const tArr = $(".ta").text(); if(tArr[0] === "黒" ){   /*wrapメソッドで個別に引数の要素で囲む*/ $(".ta").wrap("<p class='cft'></p>").text("赤"); }else{    /*unwrapメソッドで指定の要素を削除*/ $(".ta").unwrap().text("赤"); } }); }); </script> </head> <body> <div class="ta">黒</div> <div class="ta">黒</div> <input type="button" id="btnchg" value="変更"> </body> </html>
<!DOCTYPE html>
<html>
<head>
<style>
.cft{
  color:red;
 }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
     $("#btnchg").click(function() {
         const tArr = $(".ta").text();
        
            if(tArr[0] === "黒" ){
          /*wrapメソッドで個別に引数の要素で囲む*/
                  $(".ta").wrap("<p class='cft'></p>").text("赤");
            }else{
           /*unwrapメソッドで指定の要素を削除*/
                  $(".ta").unwrap().text("赤");
            }
      });
});
</script>
</head>
<body>


<div class="ta">黒</div>
<div class="ta">黒</div>

<input type="button" id="btnchg" value="変更">

</body>
</html>

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
「変更」ボタンを押すと、wrapメソッドで個別のpタグを追加します。
 <p class="cft"><div class="ta"></div></p>
再度「変更」ボタンを押すと、unwrapメソッドで指定要素の親要素を削除します
「変更」ボタンを押すと、wrapメソッドで個別のpタグを追加します。  <p class="cft"><div class="ta">赤</div></p> 再度「変更」ボタンを押すと、unwrapメソッドで指定要素の親要素を削除します
「変更」ボタンを押すと、wrapメソッドで個別のpタグを追加します。
 <p class="cft"><div class="ta">赤</div></p>
再度「変更」ボタンを押すと、unwrapメソッドで指定要素の親要素を削除します

 

jQuery

Posted by arkgame