Managing Classes
In this page:
addClass()
.addClass() appends one or more space-separated class names onto an element without disturbing any classes it already has. Adding a class that's already present has no effect, so it's always safe to call without checking first.
Example: addClass()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
.highlight { background: yellow; }
</style>
</head>
<body>
<p id="text">Text</p>
<script>
$("#text").addClass("highlight");
</script>
</body>
</html>
removeClass()
removeClass() removes one or more classes from an element, leaving any other classes untouched. Calling it with no arguments at all removes every class the element currently has.
Example: removeClass()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
.highlight { background: yellow; }
</style>
</head>
<body>
<p id="text" class="highlight bold">Text</p>
<script>
$("#text").removeClass("highlight");
</script>
</body>
</html>
toggleClass()
toggleClass() adds a class when it is missing and removes it when it already exists, flipping the element's state with a single call. This makes it the natural choice for things like show/hide toggles or active/inactive UI states.
Example: toggleClass()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
.active { background: yellow; }
</style>
</head>
<body>
<button id="btn">Toggle</button>
<script>
$("#btn").on("click", function() {
$(this).toggleClass("active");
});
</script>
</body>
</html>
hasClass()
hasClass() checks whether an element currently has a specific class and returns a plain true or false, without changing the element at all. It's commonly used to branch logic based on an element's current visual state.
Example: hasClass()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="text" class="highlight">Text</p>
<script>
console.log($("#text").hasClass("highlight"));
</script>
</body>
</html>
Working with Classes
Classes are useful for applying reusable styles and states defined once in a stylesheet, rather than setting individual CSS properties with css() every time. Toggling a class is usually cleaner than toggling several individual style properties by hand.
Example: Working with Classes
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
.highlight { background: yellow; }
</style>
</head>
<body>
<p id="text">Text</p>
<button id="btn">Style</button>
<script>
$("#btn").on("click", function() {
$("#text").toggleClass("highlight");
});
</script>
</body>
</html>
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: