toggleClass
- toggleClass()로 선택한 요소에 클래스(Class)값을 추가/삭제 할 수 있다.
// div요소에 box클래스가 없으면 추가하고, 있으면 제거한다.
$('div').toggleClass('box');
- 버튼 클릭 시 h1요소에 bgColor클래스값이 추가되어 배경색이 생기고, 다시 버튼을 클릭하면 bgColor클래스 값이 제거되어 배경색이 사라진다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>jQuery</title>
<style>
.bgColor {
background-color: #f5f5f5;
}
</style>
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$( document ).ready( function() {
$( 'button' ).click( function() {
$( 'h1' ).toggleClass( 'bgColor' );
} );
} );
</script>
</head>
<body>
<button>Click</button>
<h1>Lorem Ipsum Dolor</h1>
</body>
</html>
- 클래스에 값을 추가할 때 .addClass()
- 클래스에 값을 제거할 때 .removeClass()