출처 : https://www.w3schools.com 사이트의 내용을 공부하며 정리하고 있다.

jQuery는 HTML 요소를 삭제하기 쉽다. 


요소나 내용을 삭제하기 위해 주요한 두 개의 jQuery 메소드가 있다.

remove() : 선택된 요소와 그 자식요소를 삭제한다.

empty() : 선택된 요소로부터 자식 요소를 제거한다.


예제)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#div1").remove();
    });
});
</script>
</head>
<body>
 
<div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">
 
in div1
<p>in div2</p>
<p>in div3</p>
 
</div>
<br>
 
<button>Remove div element</button>
 
</body>
</html>
 
cs

결과 : div가 삭제된다. 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#div1").empty();
    });
});
</script>
</head>
<body>
 
<div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">
 
in div1
<p>in div2</p>
<p>in div3</p>
 
</div>
<br>
 
<button>empty div element</button>
 
</body>
</html>
cs

결과 : empty는 div 안에 있는 자식요소인 내용을 지운다.



아래 예제는 <p> 요소의 class="test"를 모두 다 삭제하는 예제이다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").remove(".test");
    });
});
</script>
<style>
.test {
    color: red;
    font-size: 20px;
}
</style>
</head>
<body>
 
<p>This is a paragraph.</p>
<p class="test">This is another paragraph.</p>
<p class="test">This is another paragraph.</p>
 
<button>Remove all p elements with class="test"</button>
 
</body>
</html>
 
cs

결과 : p 태그 중 class가 test 인 것만 삭제 된다.

'문돌이의 IT > jQuery' 카테고리의 다른 글

jQuery css() 메소드  (0) 2017.08.19
jQuery Get and Set CSS 클래스들  (0) 2017.08.15
jQuery - Add Elements  (0) 2017.08.13
jQuery - Set Content and Attributes  (0) 2017.08.12
jQuery Effects 제이쿼리 효과 - callback  (0) 2017.08.11

+ Recent posts