Add or Remove Class using JQuery
In this example, We will show you about, How add or remove class using Jquery. The example has been tested with environment and output has been shared in the same post.
JQuery Script
function chnageBackground(value) { if(value == 'R') { $('#content').removeClass("green"); $('#content').removeClass("blue"); $('#content').addClass("red"); } else if(value == 'G') { $('#content').removeClass("red"); $('#content').removeClass("blue"); $('#content').addClass("green"); } else if(value == 'B') { $('#content').removeClass("red"); $('#content').removeClass("green"); $('#content').addClass("blue"); } }
Complete Example
<html> <head> <title>How to Add or Remove Class using JQuery</title> <style> .red { background-color:red; color:white; } .green { background-color:green; color:white; } .blue { background-color:blue; color:white; } </style> </head> <body> <h1 class="yellow" id="content"> Hello World </h1> <div> <button value="R" onclick="chnageBackground(this.value);">Red</button> <button value="G" onclick="chnageBackground(this.value);">Green</button> <button value="B" onclick="chnageBackground(this.value);">Blue</button> </div> <script> function chnageBackground(value) { if(value == 'R') { $('#content').removeClass("green"); $('#content').removeClass("blue"); $('#content').addClass("red"); } else if(value == 'G') { $('#content').removeClass("red"); $('#content').removeClass("blue"); $('#content').addClass("green"); } else if(value == 'B') { $('#content').removeClass("red"); $('#content').removeClass("green"); $('#content').addClass("blue"); } } </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> </body> </html>
Output
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet