「jQuery」unwrapで要素を囲んでいるタグを削除する
環境
jQuery 3.6.0
Google Chrome 99.0.4844.51
書式
$(ボタン名).click(function(){
$(セレクター名).unwrap();
});
unwrapを使用して要素を囲んでいるタグを削除します。
対象要素を囲っているタグを削除するため、複数回実行すると親タグがどんどん消えていきます。
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
//要素を囲んでいるタグを削除
$('#btnWrap').click(function(){
$("#cft").unwrap();
});
});
</script>
</head>
<body>
<p><input type="button" id="btnWrap" value="検証"></p>
<strike style="color:red"><b><div id="cft">test sample</div></b></strike>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
//要素を囲んでいるタグを削除
$('#btnWrap').click(function(){
$("#cft").unwrap();
});
});
</script>
</head>
<body>
<p><input type="button" id="btnWrap" value="検証"></p>
<strike style="color:red"><b><div id="cft">test sample</div></b></strike>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(function(){ //要素を囲んでいるタグを削除 $('#btnWrap').click(function(){ $("#cft").unwrap(); }); }); </script> </head> <body> <p><input type="button" id="btnWrap" value="検証"></p> <strike style="color:red"><b><div id="cft">test sample</div></b></strike> </body> </html>
実行結果
「検証」ボタンを押すと、指定した要素を囲っているタグを削除します。