jQuery CSS Classes
Classes are the cleanest way to style elements, because your look-and-feel lives in your CSS file instead of scattered through your JavaScript. jQuery lets you add, remove, and flip classes on the fly, which is perfect for reacting to clicks, form errors, or any change in state.
Working with CSS classes
Instead of setting individual style properties one by one, you define the styles once in a class and then let jQuery attach or detach that class. This keeps your code readable and your styling in one place.
- addClass() - applies one or more classes to the selected elements.
- removeClass() - takes one or more classes off the selected elements.
- toggleClass() - adds the class if it is missing and removes it if it is already there.
- hasClass() - returns true or false depending on whether a class is present.
Add and remove classes
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<ul>
<li>Item one</li>
<li>Item two</li>
<li>Item three</li>
</ul>
<script>
// Highlight all list items
$("li").addClass("highlight");
// Remove the highlight later
$("li").removeClass("highlight");
</script>
</body>
</html>Toggling a class
toggleClass() is ideal for on/off behavior such as showing a dark theme or opening a menu. Each click flips the class between present and absent.
Flip a class on each click
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="themeBtn">Toggle theme</button>
<script>
$("#themeBtn").click(function () {
$("body").toggleClass("dark-mode");
});
</script>
</body>
</html>Add more than one class at once
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="card">Card content</div>
<script>
// Separate multiple class names with spaces
$("#card").addClass("rounded shadow bordered");
</script>
</body>
</html>Note: Calling removeClass() with no argument removes every class from the element. Pass a specific name when you only want to drop one.
Exercise: jQuery CSS Classes
What does $(x).toggleClass("active") do?