jQuery / Reference / .toggleClass()
.toggleClass("active")는 선택된 요소에 active가 있으면 빼고 없으면 넣습니다. .toggleClass("active", enabled)는 enabled가 true면 넣고 false면 뺍니다. 각각 클릭으로 반전할 때와 이미 정해진 상태를 반영할 때 사용합니다.
클래스를 반전하거나 상태를 지정하는 문법
클래스 이름은 "active"처럼 점 없이 씁니다. 상태 인수에는 실제 불리언 값인 true 또는 false를 넘겨야 합니다. 문자열 "false"나 숫자 0은 같은 뜻으로 처리되지 않습니다. 아래 세 줄은 독립적인 호출 예입니다. jQuery API — .toggleClass()
$("#by-button").toggleClass("active");
$("#by-button").toggleClass("active", true);
$("#by-button").toggleClass("active", false);
버튼을 누를 때마다 강조를 바꾸는 예제
전체 코드를 UTF-8로 jquery-toggleclass.html에 저장하고 브라우저에서 엽니다. 공식 CDN에서 jQuery 4.0.0을 불러오므로 인터넷 연결이 필요합니다. 첫 문단은 버튼, 둘째 문단은 체크박스로 조작합니다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery .toggleClass() 예제</title>
<style>
body { margin: 24px; font: 1rem/1.6 system-ui, sans-serif; overflow-wrap: anywhere; }
button, input { font: inherit; }
.base { padding: .65rem; border: 2px solid #a1a7ad; border-radius: .4rem; }
.active { background: #fff0b3; border-color: #08716d; font-weight: 700; }
</style>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
</head>
<body>
<main>
<h1>jQuery .toggleClass() 예제</h1>
<button id="toggle" type="button" aria-pressed="false">버튼 강조 전환</button>
<p id="by-button" class="base">버튼으로 바꾸는 문단</p>
<p id="button-state" role="status"></p>
<label><input id="option" type="checkbox"> 체크박스 강조 적용</label>
<p id="by-option" class="base">체크박스를 따라가는 문단</p>
<p id="option-state" role="status"></p>
</main>
<script>
$(function () {
const $button = $("#toggle");
const $option = $("#option");
const $byButton = $("#by-button");
const $byOption = $("#by-option");
const on = "강조 켜짐";
const off = "강조 꺼짐";
function showButtonState() {
const enabled = $byButton.hasClass("active");
$button.attr("aria-pressed", String(enabled));
$("#button-state").text(enabled ? on : off);
}
function syncOption() {
const enabled = $option.prop("checked");
$byOption.toggleClass("active", enabled);
$("#option-state").text(enabled ? on : off);
}
$button.on("click", function () {
$byButton.toggleClass("active");
showButtonState();
});
$option.on("change", syncOption);
showButtonState();
syncOption();
});
</script>
</body>
</html>
버튼을 처음 누르면 첫 문단이 강조되고 상태 문구가 강조 켜짐으로 바뀝니다. 다시 누르면 active가 사라집니다. Tab으로 버튼에 이동한 뒤 Enter나 Space를 눌러도 같은 결과를 확인할 수 있습니다.
체크박스 상태와 표시를 일치시키기
체크박스를 선택하면 둘째 문단에 active가 생기고 선택을 해제하면 사라집니다. 코드는 .prop("checked")로 읽은 불리언을 그대로 넘깁니다. 체크 상태가 그대로인 채 동기화가 다시 실행되어도 강조는 반전되지 않습니다. 코드에서 페이지가 준비될 때도 동기화하는 이유입니다.
예제의 토글 버튼은 표시 이름을 유지하면서 aria-pressed 값을 현재 상태에 맞춥니다. 체크박스는 자체 선택 상태를 전달합니다. CSS 클래스를 바꿔도 접근성 상태 속성이 자동으로 바뀌지는 않습니다. WAI-ARIA APG — Button Pattern
여러 클래스의 상태를 바꿀 때
클래스 이름을 공백으로 구분하거나 jQuery 3.3 이상에서 배열로 전달할 수 있습니다. 상태 인수가 없으면 각 이름을 따로 반전합니다. 아래 코드를 예제 콘솔에서 실행하면 첫 호출은 active를 빼고 marked를 넣습니다. 다음 호출은 두 이름을 모두 있게 합니다.
const $item = $('<p class="base active"></p>');
$item.toggleClass("active marked");
console.log($item.attr("class")); // base marked
$item.toggleClass(["active", "marked"], true);
console.log($item.attr("class")); // base marked active
jQuery 4.0 변경점과 문제 확인
jQuery 4.0에서는 클래스 이름 없이 전체 클래스 목록을 바꾸던 .toggleClass()와 .toggleClass(state) 형태가 제거됐습니다. 4.0에서도 .toggleClass("active", state)는 쓸 수 있습니다. jQuery 4.0 Upgrade Guide
결과가 예상과 다르면 요소 탭에서 active가 실제로 바뀌는지, 상태 값이 불리언인지 확인하세요. 클래스가 바뀌는데 모양이 그대로라면 해당 CSS 규칙이나 우선순위를 살핍니다. 상태와 관계없이 항상 넣거나 뺄 때는 .addClass() 또는 .removeClass()를 사용합니다.




