AD JB Toolbox 01

jQuery / Reference / .toggleClass()

.toggleClass("클래스")는 클래스가 있으면 제거하고 없으면 추가합니다. 두 번째 인수로 true 또는 false를 전달하면 현재 상태와 관계없이 추가·제거 여부를 명시할 수 있습니다.

문법과 적용 범위

$("#item").toggleClass("active");
$("#item").toggleClass("active", true);
$("#item").toggleClass("active", false);

상태를 반전하는 동작과 상태를 지정하는 동작은 다릅니다. 클릭할 때마다 강조를 바꾸려면 첫 형태를, 서버나 체크박스의 상태를 화면에 반영하려면 두 번째 형태를 사용합니다. state 인수는 문자열 "false"나 숫자 0이 아니라 실제 불리언(Boolean) 값이어야 합니다. 여러 클래스도 공백으로 구분해 지정할 수 있으며 각 이름이 개별적으로 처리됩니다.

jQuery 공식 문서의 .toggleClass() 정의와 인수에서 다른 호출 형태도 확인할 수 있습니다.

전체 실행 예제

아래 코드를 UTF-8 형식의 example.html 파일로 저장한 뒤 브라우저로 여세요. 예제는 jQuery 4.0.0 일반 빌드를 외부 주소에서 불러오므로 인터넷 연결이 필요합니다. 문서가 준비된 뒤 실행하도록 $(function () { ... }) 안에 코드를 작성했습니다.

<!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-family: sans-serif; line-height: 1.6; }
    .marked { background: #fff0b3; border: 2px solid #835b00; }
    .active { color: #a00000; font-weight: bold; }
    button, input, select { font: inherit; }
    #output { white-space: pre-wrap; overflow-wrap: anywhere; }
  </style>
  <script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
</head>
<body>
<button id="toggle" type="button" aria-pressed="false">강조 전환</button>
<p id="item" class="base">전환할 문단</p>
  <p id="output" aria-live="polite"></p>
  <script>
    $(function () {
      $("#toggle").on("click", function () {
        $("#item").toggleClass("active");
        const enabled = $("#item").hasClass("active");
        $(this).attr("aria-pressed", String(enabled));
        $("#output").text("강조: " + enabled);
      });
    });
  </script>
</body>
</html>

실행 결과 확인

버튼을 처음 누르면 문단이 붉은색으로 강조되고 강조: true가 표시됩니다. 다시 누르면 클래스가 제거되고 강조: false가 됩니다. aria-pressed도 같은 상태로 바뀌어 버튼의 눌림 상태를 전달합니다.

사용할 때 주의할 점

  • 조건에 따라 특정 상태로 맞출 때 단순 반전을 반복하면 실제 상태와 화면이 어긋날 수 있습니다. .toggleClass("active", enabled)로 조건을 전달하세요.
  • jQuery 4.0에서는 클래스 이름 없이 전체 클래스를 전환하던 .toggleClass()와 .toggleClass(state) 형태가 제거됐습니다. 전환할 클래스 이름을 명시하세요.
  • 클래스만 바꾸는 것은 요소를 숨기거나 접근성 상태를 갱신하는 것과 별개입니다. 제어 목적에 맞는 CSS와 aria 속성을 함께 관리하세요.

용도를 비교하려면 .addClass()로 항상 추가하기, .removeClass()로 항상 제거하기을 참고하세요.

같은 카테고리의 다른 글
jQuery / Reference / .width()

jQuery / Reference / .width()

내용 너비와 padding·border를 포함한 너비를 비교하고, border-box에서 width를 읽고 설정하는 결과를 설명합니다.

jQuery / Reference / :contains()

jQuery / Reference / :contains()

텍스트의 부분 일치와 대소문자 구분을 예제로 확인하고, 자식 텍스트와 동적인 검색어를 처리하는 방법을 설명합니다.

jQuery / Reference / .has()

jQuery / Reference / .has()

특정 자손을 가진 원래 요소를 골라내는 방법을 확인하고, find와 결과 대상이 어떻게 다른지 설명합니다.

jQuery / Reference / .find()

jQuery / Reference / .find()

현재 요소를 제외한 자손 탐색 범위를 확인하고, children·filter·has와 용도 차이를 설명합니다.

jQuery / Reference / .slideUp()

jQuery / Reference / .slideUp()

내용을 접어 숨기는 문법과 시간·easing·완료 콜백을 설명하고, 연속 클릭과 처음 상태로 되돌리는 예제를 제공합니다.

jQuery / Reference / .remove()

jQuery / Reference / .remove()

선택 요소와 자손을 제거하는 방법, 조건 선택자의 범위 및 empty·detach와의 차이를 설명합니다.

jQuery / Reference / .empty()

jQuery / Reference / .empty()

컨테이너를 남기고 내부 요소와 텍스트를 비우는 방법과 다시 채우기, 이벤트·입력값의 처리 범위를 설명합니다.

jQuery / Reference / .val()

jQuery / Reference / .val()

현재 입력값과 다중 선택 값을 읽고 설정하는 방법, change 이벤트와 체크 상태의 차이를 설명합니다.

jQuery / Reference / .after()

jQuery / Reference / .after()

대상의 뒤에 형제 요소를 추가하는 방법과 기존 요소 이동, append 및 insertAfter와의 차이를 설명합니다.

jQuery / Reference / .wrapAll()

jQuery / Reference / .wrapAll()

여러 요소를 하나의 부모로 모으는 방법과 중간 형제의 처리, 위치 이동 및 감싸기 해제의 한계를 설명합니다.