In this article, you will learn how to add or remove the CSS classes from the HTML elements dynamically using jQuery.
- Download Jquery Plugin or Use CDN Link
- Make HTML Form
- Add Jquery Library
- Use jquery onclick function
- Define jQuery addclass
- Define jQuery removeclass
Create new html file
At first you have create new html file in your specific path . Then open the html file that will display the data and add the following code
index.html
<!DOCTYPE html><html><head><title>Jquery Add and Remove Classes</title><meta charset="utf-8"></head><style>.red{color:red;}.blue{color:blue;}</style><body><h1>Heading 1</h1><h2>Heading 2</h2><button class="a_clickme">Add classes</button><button class="r_clickme">Remove classes</button></body></html>
Set Jquery Plugin
Then, You add jquery plugin in your file
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
Define Add and Remove Classes
Then, use jQuery onclick function and define the jquery addClass() and removeClass() use to sample syntax
addClass() and removeClass()
<script>$(document).ready(function(){$(".a_clickme").click(function(){$("h1").addClass("red");});});$(document).ready(function(){$(".r_clickme").click(function(){$("h1").removeClass("red");});});</script>
Full Source Code
<!DOCTYPE html><html><head><title>Jquery Add and Remove Classes</title><meta charset="utf-8"><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script></head><style>.red{color:red;}.blue{color:blue;}</style><body><h1>Heading 1</h1><h2>Heading 2</h2><button class="a_clickme">Add classes</button><button class="r_clickme">Remove classes</button></body><script>$(document).ready(function(){$(".a_clickme").click(function(){$("h1").addClass("red");});});$(document).ready(function(){$(".r_clickme").click(function(){$("h1").removeClass("red");});});</script></html>
Finally enter your project url in browser
Output
Before
After
Conclusion
We hope this guide has been helpful. If you have any questions or need further assistance, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.
0 Comments