HOWTO · jQuery
jQuery remove() 메서드
이 튜토리얼은 jQuery에서 요소를 제거하는 방법을 보여줍니다.
이 페이지의 내용
remove() 메소드는 jQuery의 DOM에서 요소를 제거합니다. 마찬가지로 empty() 메서드는 DOM에서 선택한 요소의 자식 요소만 제거합니다.
이 튜토리얼은 jQuery에서 remove 및 empty 메소드를 사용하는 방법을 보여줍니다.
jQuery remove() 메소드
remove() 메소드는 DOM에서 선택된 요소를 제거할 수 있습니다. 이 메서드는 선택한 요소와 요소 내부의 모든 것을 제거합니다.
이 메서드의 구문은 다음과 같습니다.
$(selector).remove(selector)
selector가 하나 이상의 요소를 제거할지 여부를 지정하는 선택적 매개변수인 경우 제거할 요소가 둘 이상인 경우 쉼표로 구분할 수 있습니다. 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, 클래스 또는 요소 이름이 될 수 있는 경우 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의 자식 콘텐츠만 제거합니다. 출력 참조: