In jQuery, we can use addClass()
and removeClass()
methods to add and remove classes from an element. Here is a live example with code :
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add and Remove Classes with jQuery</title>
<link rel="stylesheet" href="styles.css">
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>
<div id="myElement">This is a div</div>
<button id="addClass">Add Class</button>
<button id="removeClass">Remove Class</button>
<script src="script.js"></script>
</body>
</html>
CSS
.highlight {
background-color: yellow;
}
JavaScript
$(document).ready(function () {
$("#addClass").on("click", function () {
$("#myElement").addClass("highlight");
});
$("#removeClass").on("click", function () {
$("#myElement").removeClass("highlight");
});
});