JS 관련/JQuery

[jQuery] 엘리먼트 제거( remove(), empty(), detach() )

씨네 2022. 2. 27. 14:08
728x90

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
div{border: 1px solid red; width: 200px; padding: 10px 10px;}
p{background: yellow;}
h1{border: 1px solid blue;}
</style>
<script type="text/javascript" src="resources/js/jquery-3.5.1.min.js"></script>
<script type="text/javascript">

	$(document).ready(function(){
		$("p:eq(0)").click(function(){
			// remove : 삭제
			$(this).remove();
		});
		
		$("p:eq(1)").click(function(){
			// empty : 내부요소 삭제
			$(this).parent().empty();
		});
		
		$("p:eq(2)").click(function(){
			// detach : 잘라내기
			var ele = $(this).detach();
			$("h1").append(ele);
		});
		
	});
	
</script>
</head>
<body>

	<h1>엘리먼트 제거</h1>

	<div>
		<p>remove</p>
		<p>empty</p>
		<p>detach</p>
		
	</div>
</body>
</html>

$("p:eq(0)").click(function(){
	// remove : 삭제
	$(this).remove();
});

remove는 말그대로 삭제입니다.

$("p:eq(1)").click(function(){
	// empty : 내부요소 삭제
	$(this).parent().empty();
});

empty는 내부요소 삭제입니다.

(this) 자신의 parent() 부모의 내부요소니까 형제요소들을 전부 삭제하겠죠?

$("p:eq(2)").click(function(){
	// detach : 잘라내기
	var ele = $(this).detach();
	$("h1").append(ele);
});

 

detach는 잘라내기 역할인데 detach()이후 변수에 담아서 다른곳에 추가할수 있습니다.

728x90