jQuery wrapInnerで指定html要素の中でhtmnlタグを挿入するサンプル

環境
Google Chrome 105.0.5195.127
Windows 10 Home 64bit
jquery 3.6.1

書式
$('指定要素’).wrapInner('htmlタグを指定’)
wrapInnerメソッドを使って指定したhtmlタグの中にhtmlタグを挿入します。
wrapInnerで指定の要素の下で個別に要素(タグ)で囲みます。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<style>
.rr{color:red;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(function () {
$("#btntest").click(function() {
const res = $(".yu").text();
if(res[0] === "黒" ){
$(".yu").wrapInner("<span class='rr'>");
$(".rr").text("青");
}else{
$(".rr").remove();
$(".yu").text("黒");
}
});
})
</script>
</head>
<body>
<p class="yu"></p>
<input type="button" id="btntest" value="テスト">
</body>
</html>
<!DOCTYPE html> <html> <head> <style> .rr{color:red;} </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(function () { $("#btntest").click(function() { const res = $(".yu").text(); if(res[0] === "黒" ){ $(".yu").wrapInner("<span class='rr'>"); $(".rr").text("青"); }else{ $(".rr").remove(); $(".yu").text("黒"); } }); }) </script> </head> <body> <p class="yu">黒</p> <input type="button" id="btntest" value="テスト"> </body> </html>
<!DOCTYPE html>
<html>
<head>
<style>
.rr{color:red;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(function () {

      $("#btntest").click(function() {
            const res = $(".yu").text();

            if(res[0] === "黒" ){
                  $(".yu").wrapInner("<span class='rr'>");
                  $(".rr").text("青");

            }else{
                  $(".rr").remove();
                  $(".yu").text("黒");
            }
      });

})
</script>
</head>
<body>

<p class="yu">黒</p>

<input type="button" id="btntest" value="テスト">

</body>
</html>

実行結果
「テスト」ボタンを押すと、「<span class=’s1′>」タグを追加します。

jQuery

Posted by arkgame