agyanadda@gmail.com

jQuery CSS Classes

jQuery HTML and CSS 1 min read Updated Dec 1, 2026 Topic 13 of 25

The best way to change design with jQuery is to switch CSS classes — keep the styles in CSS.

Method Does
.addClass('active') add a class
.removeClass('active') remove a class
.toggleClass('active') add or remove
.hasClass('active') check (true / false)

Several classes: .addClass('card shadow').

Active menu pattern

$('.tab').click(function () {
  $('.tab').removeClass('active');
  $(this).addClass('active');
});

Toggle with a condition

.toggleClass('dark', isNight) — add when true, remove when false.

Example

Example β€” Active menu and dark mode HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
  body { transition: background .3s, color .3s; font-family: Arial, sans-serif; }
  body.dark { background: #1e1e1e; color: #eee; }
  .menu a { display:inline-block; padding:8px 14px; text-decoration:none; color:inherit; border-radius:6px; }
  .menu a.active { background:#1f386b; color:#fff; }
</style>

<nav class="menu">
  <a href="#" class="active">Home</a>
  <a href="#">Tutorials</a>
  <a href="#">Exams</a>
</nav>
<p><button id="theme">πŸŒ™ Dark mode</button></p>

<script>
  $(function () {
    $('.menu a').click(function (e) {
      e.preventDefault();
      $('.menu a').removeClass('active');
      $(this).addClass('active');
    });
    $('#theme').click(function () {
      $('body').toggleClass('dark');
      $(this).text($('body').hasClass('dark') ? 'β˜€οΈ Light mode' : 'πŸŒ™ Dark mode');
    });
  });
</script>

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which method checks if an element has a class?

Exercise 2 True / False

toggleClass adds the class if it is missing and removes it if present.

Exercise 3 Fill in the Blank

$('#box').___Class('red') removes the class red.

Frequently Asked Questions

Styles stay in your CSS file, are easier to change later, and can use hover states, media queries and transitions.