jquery 指定したhtmlタグをhtmlタグで囲んでいく

jqueryで、指定したhtmlタグをhtmlタグで囲んでいくサンプルコードを記述してます。「wrap」メソッドを使用します。
環境
- OS windows10 pro 64bit
- jquery 3.6.0
- Apache 2.4.43
- ブラウザ chrome 91.0.4472.77
指定したhtmlタグをhtmlタグで囲んでいく
指定したhtmlタグをhtmlタグで囲んでいくには「wrap」を使用します。
$("要素を指定").wrap("htmlタグ")
以下は、「実行」ボタンをクリックすると、「id=”lab”」に親となるhtmlタグを追加するサンプルコードを記述してます。
※デザインは「semantic-ui」を使用してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<!-- semantic.css -->
<link rel="stylesheet" type="text/css"
href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
<script src="http://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<style>
body>.grid {
height: 100%;
}
.fields {
margin-top: 5px;
}
</style>
<script>
$(function () {
$('#btn').on('click', function () {
$('#lab').wrap('<div id="foo" style="background-color: #000;"></div>')
})
})
</script>
<body>
<div class="ui middle aligned center aligned grid">
<div class="column">
<a id="lab" class="ui red tag label">elm</a>
<div class="ui stackable fields">
<button id="btn" class="ui gray basic button">実行</button>
</div>
</div>
</div>
</body>
</html>
追加されていることが確認できます。

また、以下のようにアロー関数を使用して記述することも可能です。
※アロー関数を使用するとthisの挙動が異なります。
$(() => {
$('#btn').on('click', () => {
$('#lab').wrap('<div id="foo" style="background-color: #000;"></div>')
})
})
-
前の記事
sqlite default値が反映されない 2022.03.04
-
次の記事
Vue.js v-bindでクラス名を指定する 2022.03.04
コメントを書く