Classes and CSS

Add, remove, and toggle classes, or set styles directly.

Syntax$(el).addClass("x"); $(el).toggleClass("x"); $(el).css("color", "red");

Prefer classes for styling so your look stays in CSS:

  • .addClass("name") — add a class.
  • .removeClass("name") — remove a class.
  • .toggleClass("name") — add if missing, remove if present.
  • .hasClass("name") — test for a class.

.css() sets inline styles directly when you need a quick one-off change.

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A dark-mode toggle calls .toggleClass('dark') on <body> each time the user clicks the theme switch button.
  • A validation script adds the .error class to an input and removes it when the user corrects the value.
  • A dashboard card uses .css({ opacity: 0.5, pointerEvents: 'none' }) to visually disable itself during loading.

More examples

Add and remove a CSS class

.addClass() and .removeClass() mutate the class list without affecting other classes already on the element.

Example · html
<p id="para">Plain paragraph.</p>
<button id="add">Add highlight</button>
<button id="rem">Remove highlight</button>
<style>.highlight { background: yellow; font-weight: bold; }</style>
<script>
$(function () {
  $("#add").click(function () { $("#para").addClass("highlight"); });
  $("#rem").click(function () { $("#para").removeClass("highlight"); });
});
</script>

Toggle dark mode on body

.toggleClass() adds the class if absent or removes it if present, making a one-button theme switch trivial.

Example · html
<style>
  .dark { background: #111; color: #eee; }
</style>
<button id="themeToggle">Toggle dark mode</button>
<p>Some page content here.</p>
<script>
$(function () {
  $("#themeToggle").click(function () {
    $("body").toggleClass("dark");
  });
});
</script>

Apply inline styles with .css()

Passing an object to .css() applies multiple inline style properties in a single method call.

Example · html
<div id="card" style="padding:16px;border:1px solid #ccc;">Card content</div>
<button id="style">Style card</button>
<script>
$(function () {
  $("#style").click(function () {
    $("#card").css({
      border: "2px solid #3498db",
      borderRadius: "8px",
      boxShadow: "0 4px 12px rgba(0,0,0,.15)"
    });
  });
});
</script>

Discussion

  • Be the first to comment on this lesson.
Classes and CSS — jQuery | SoundsCode