December 15, 2024
Add and remove css class using JavaScript
We can use JavaScript to add or remove CSS classes from elements. There are several methods available for this purpose. The first method is the classList.add / classList.remove functions, which allows us to add/remove a CSS class to a selected element.
add class/remove class example
<html>
<head>
<title>Example </title>
<style>
.greenTextClass{color:'green';}
.redTextClass{color:'red';}
</style>
</head>
<body>
<input type="text" id="textElem" value="Sample Text">
<button id="btnGreenElem" onclick="changeGreenText()">Green Text</button>
<button id="btnRedElem" onclick="changeRedText()">Red Text</button>
<script>
function changeGreenText() {
document.getElementById("textElem").classList.add("greenTextClass");
document.getElementById("textElem").classList.remove("redTextClass");
};
function changeRedText() {
document.getElementById("textElem").classList.add("redTextClass");
document.getElementById("textElem").classList.remove("greenTextClass");
};
</script>
</body>
</html>