jQueryで要素を空にするemptyと削除するremoveの使い方
jQueryにおける要素の削除系メソッドについてまとめました。
指定した要素を空にするempty()
セレクタで指定した要素の中身(子要素)を削除し、空にするには$(要素).empty()を使用します。
サンプルコード
<ul>
<li class="test1">リスト1</li>
<li class="test2">リスト2</li>
<li class="test3">リスト3</li>
</ul>
<script>
$(function(){
$('.test2').empty();
});
</script>
- リスト1
- リスト2
- リスト3
あくまで「要素の中身を削除する」処理であり、要素そのものを削除するわけではありません。
実質的には、html()メソッドに空文字を代入することと同じ処理です。
サンプルコード
<ul>
<li class="test1">リスト1</li>
<li class="test2">リスト2</li>
<li class="test3">リスト3</li>
</ul>
<script>
$(function(){
$('.test2').html('');
});
</script>
- リスト1
- リスト2
- リスト3
指定した要素を削除するremove()
セレクタで指定した要素そのものの削除は$(要素).remove()を使用します。
サンプルコード
<ul>
<li class="test1">リスト1</li>
<li class="test2">リスト2</li>
<li class="test3">リスト3</li>
</ul>
<script>
$(function(){
$('.test2').remove();
});
</script>
- リスト1
- リスト2
- リスト3
remove()はempty()と異なり、要素そのものを抹消します。
以上、jQueryで要素を空にするemptyと削除するremoveの使い方、でした。


ディスカッション
コメント一覧
まだ、コメントがありません