How to Add or Remove Class using JQuery

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

How to Add or Remove Class using JQuery  how to square a number in java