TExcelTAD
Home › jQuery › jQuery CSS Classes

jQuery CSS Classes

The cleanest way to change how something looks with JavaScript is not to set individual styles, but to add or remove a CSS class whose rules live in your stylesheet. That keeps design in CSS and behaviour in JavaScript.

The class methods

Method What it does
.addClass("a b") Adds one or more classes (space-separated)
.removeClass("a") Removes classes; .removeClass() with no argument removes all
.toggleClass("a") Adds if missing, removes if present
.toggleClass("a", state) true → add, false → remove
.hasClass("a") true if any matched element has the class

Since jQuery 3.3, addClass, removeClass and toggleClass also accept an array of class names: .addClass(["big", "blue"]).

html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; }
    .card { width: 240px; padding: 12px; border: 1px solid #ccc; border-radius: 8px; transition: all .2s; }
    .highlight { background: #fff8d6; border-color: #e0b400; }
    .big { font-size: 20px; }
    .dark { background: #222; color: #eee; border-color: #000; }
  </style>
</head>
<body>
  <button id="add">addClass("highlight big")</button>
  <button id="rem">removeClass("big")</button>
  <button id="tog">toggleClass("dark")</button>
  <button id="clr">removeClass()</button>
  <div class="card" id="c">Watch my classes change.</div>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    const show = () => console.log("class attribute:", JSON.stringify($("#c").attr("class")));
    $("#add").on("click", () => { $("#c").addClass("highlight big"); show(); });
    $("#rem").on("click", () => { $("#c").removeClass("big"); show(); });
    $("#tog").on("click", () => { $("#c").toggleClass("dark"); show(); });
    $("#clr").on("click", () => { $("#c").removeClass().addClass("card"); show(); });
  </script>
</body>
</html>

Tip: The transition in the CSS makes class changes animate smoothly — including colours, which jQuery's own .animate() cannot do.

Active state in a group

A very common pattern: in a group of buttons or tabs, exactly one is "active". Remove the class from all, then add it to the clicked one:

html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; }
    .tabs button { padding: 6px 14px; border: 1px solid #0769ad; background: #fff; color: #0769ad; cursor: pointer; }
    .tabs button.active { background: #0769ad; color: #fff; }
    .pane { display: none; padding: 10px; border: 1px solid #0769ad; width: 280px; }
    .pane.active { display: block; }
  </style>
</head>
<body>
  <div class="tabs">
    <button class="active" data-pane="home">Home</button><button data-pane="profile">Profile</button><button data-pane="settings">Settings</button>
  </div>
  <div class="pane active" id="home">Welcome home!</div>
  <div class="pane" id="profile">Your profile details.</div>
  <div class="pane" id="settings">Change your settings here.</div>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    $(".tabs button").on("click", function () {
      const id = $(this).data("pane");
      $(this).addClass("active").siblings().removeClass("active");
      $(".pane").removeClass("active");
      $("#" + id).addClass("active");
      console.log("active tab:", id);
    });
  </script>
</body>
</html>

.siblings() returns the other buttons in the same parent, so $(this).addClass("active").siblings().removeClass("active") handles the whole group in a single chain.

toggleClass with a condition

The second argument of .toggleClass() turns it into "add if the condition is true, otherwise remove". This removes a lot of if/else code, for instance in form validation:

html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; }
    input { padding: 6px; border: 2px solid #ccc; border-radius: 4px; outline: none; }
    input.valid { border-color: #2e7d32; }
    input.invalid { border-color: #c62828; }
    .hint { font-size: 13px; color: #c62828; }
    .hint.hidden { visibility: hidden; }
  </style>
</head>
<body>
  <label>Username (3–12 letters or digits)</label><br>
  <input id="user" autocomplete="off">
  <div class="hint hidden" id="hint">Only 3–12 letters or digits, please.</div>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    $("#user").on("input", function () {
      const value = $(this).val();
      const ok = /^[a-z0-9]{3,12}$/i.test(value);
      const empty = value === "";
      $(this)
        .toggleClass("valid", ok)
        .toggleClass("invalid", !ok && !empty);
      $("#hint").toggleClass("hidden", ok || empty);
      console.log(JSON.stringify(value), ok ? "valid" : "invalid");
    });
  </script>
</body>
</html>

Function arguments

Like other setters, the class methods accept a function, called once per element with its index and current class string:

js
// zebra striping with a function
$("tr").addClass(function (index) {
  return index % 2 === 0 ? "even-row" : "odd-row";
});

Classes vs inline styles

Approach Example Pros Cons
Toggle a class .addClass("error") Styles stay in CSS; easy to change design; supports transitions, media queries, :hover Needs a CSS rule
Inline style .css("color", "red") Quick for computed values (positions, sizes) Mixes design into JS; overrides stylesheet rules

Use classes for states (active, error, hidden, selected). Use .css() (next lesson) for values that are calculated at runtime.

Test yourself

What does $("#x").toggleClass("on", false) do?

  1. Adds on
  2. Removes on
  3. Toggles on
  4. Throws an error

$("p").hasClass("note") — the page has three paragraphs and only the second has class note. Result?

  1. false
  2. true
  3. [false, true, false]
  4. 1

Which chain makes the clicked tab the only active one in its group?

  1. $(this).addClass("active").siblings().removeClass("active")
  2. $(this).toggleClass("active")
  3. $(".tab").addClass("active")
  4. $(this).siblings().addClass("active")