HOWTO · jQuery
jQuery remove() メソッド
このチュートリアルでは、jQuery で要素を削除する方法を示します。
このページの内容
remove() メソッドは、jQuery の DOM から要素を削除します。同様に、empty() メソッドは、DOM 内の選択された要素の子要素のみを削除します。
このチュートリアルでは、jQuery で remove メソッドと empty メソッドを使用する方法を示します。
jQuery remove() メソッド
remove() メソッドは、選択した要素を DOM から削除できます。このメソッドは、選択した要素と要素内のすべてを削除します。
このメソッドの構文は次のとおりです。
$(selector).remove(selector)
selector が 1つ以上の要素を削除するかどうかを指定するオプションのパラメーターである場合、削除する要素が複数ある場合は、それらをコンマで区切ることができます。remove() メソッドの例を試してみましょう。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#RemoveDiv").remove();
});
});
</script>
</head>
<body>
<div id="RemoveDiv" style="height:200px; width:300px; border:1px solid black; background-color:lightblue;">
<h1> This Div Will be Removed </h1>
<p>Paragraph one in the Div.</p>
<p>Paragraph two in the Div.</p>
</div>
<br>
<div style="height:200px; width:300px; border:1px solid black; background-color:lightblue;">
<h1> This Div Will not be Removed </h1>
<p>Paragraph one in the Div.</p>
<p>Paragraph two in the Div.</p>
</div>
<button>Remove Div</button>
</body>
</html>
上記のコードは、選択した div とその子要素を削除します。出力を参照してください:
ご覧のとおり、remove() メソッドは、選択した要素内のすべての要素を削除します。別のメソッド empty() は、子要素のみを削除します。
jQuery empty() メソッド
empty() メソッドは、選択した要素からすべての子要素を削除できます。また、子要素内のコンテンツも削除されます。
empty() メソッドの構文は次のとおりです。
$('selector').empty();
selector が id、class、または要素名である場合、empty メソッドの例を試してみましょう。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#RemoveDiv").empty();
});
});
</script>
</head>
<body>
<div id="RemoveDiv" style="height:200px; width:300px; border:1px solid black; background-color:lightblue;">
Hello this is the div content
<h1> This Div Content Will be Removed </h1>
<p>Paragraph one in the Div.</p>
<p>Paragraph two in the Div.</p>
</div>
<br>
<div style="height:200px; width:300px; border:1px solid black; background-color:lightblue;">
<h1> This Div Content Will not be Removed </h1>
<p>Paragraph one in the Div.</p>
<p>Paragraph two in the Div.</p>
</div>
<button>Remove Div</button>
</body>
</html>
上記のコードは、div 自体ではなく、div の子コンテンツのみを削除します。出力を参照してください: