December 14, 2024
Add and remove css class using jQuery
We can use jQuery to add or remove CSS classes from elements. There are several methods available for this purpose. The first method is the addClass/removeClass functions, which allows us to add/remove a CSS class to a selected element. The second method is toggleClass, which can both add and remove a CSS class from a selector, depending on its current state.
addClass/removeClass example
<html>
<head>
<title>Example if checkbox is checked in JQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.greenTextClass{color:'green';}
.redTextClass{color:'red';}
</style>
</head>
<body>
<input type="text" id="textElem" value="Sample Text">
<button id="btnGreenElem">Green Text</button>
<button id="btnRedElem">Red Text</button>
<script>
$(document).ready(function () {
$('#btnGreenElem').on('click', function () {
$("#textElem").addClass("greenTextClass");
$("#textElem").removeClass("redTextClass");
});
$('#btnRedElem').on('click', function () {
$("#textElem").addClass("redTextClass");
$("#textElem").removeClass("greenTextClass");
});
});
</script>
</body>
</html>
toggleClass example
<html>
<head>
<title>Example if checkbox is checked in JQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.greenTextClass{color:'green';}
</style>
</head>
<body>
<input type="text" id="textElem" value="Sample Text">
<button id="btnGreenElem">Green Text</button>
<script>
$(document).ready(function () {
$('#btnGreenElem').on('click', function () {
$("#textElem").toggleClass("greenTextClass");
});
});
</script>
</body>
</html>