About Lesson
Class Manipulation in jQuery:
In this lesson, you will learn how to manipulate CSS classes of HTML elements using jQuery methods. These methods make it easy to add, remove, or toggle classes dynamically.
1. .addClass() Method
The .addClass()
method is used to add one or more classes to an element. If the class already exists, it is not added again.
Add Class
To add a class to an element:
JavaScript
$("#box").addClass("highlight");
2. .removeClass() Method
The .removeClass()
method removes one or more classes from an element.
Remove Class
To remove a class from an element:
JavaScript
$("#box").removeClass("highlight");
3. .toggleClass() Method
The .toggleClass()
method toggles between adding and removing a class. If the element already has the class, it is removed; if it doesn’t, the class is added.
Toggle Class
To toggle a class on an element:
JavaScript
$("#box").toggleClass("highlight");
Practical Example:
JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Class Manipulation in jQuery</title>
<style>
.highlight {
background-color: yellow;
color: red;
}
#box {
width: 200px;
height: 200px;
border: 1px solid black;
text-align: center;
line-height: 200px;
}
</style>
</head>
<body>
<div id="box">Click me!</div>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
$(document).ready(function() {
// Add class
$("#box").addClass("highlight");
// Remove class
setTimeout(function() {
$("#box").removeClass("highlight");
}, 2000); // Remove after 2 seconds
// Toggle class
$("#box").click(function() {
$(this).toggleClass("highlight");
});
});
</script>
</body>
</html>