Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   
   HTML   
   CSS   
   JAVA SCRIPT   
   JQUERY   




CSS METHODS - addClass()


The addClass() method in JQuery is used to insert a CSS class to an element/elements.


Example :



<html>
    <head>
    	<title> My First Programme </title>
  	</head>

	<style>
    	.myClass {
        	background-color: violet;
        }
    </style>
    
  	<body>
    	<h1> JQuery </h1>
    	<p>New Code</p>
    	
    	<button> Click Here </button>
    	
      	<script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script>
	  
      	<script>
      
      		$('button').click( function() {
				$('p').addClass("myClass");
			});
			
      	</script>      
   </body>
</html>


Output :




So, in the above code, we have a <p> element,


<p>New Code</p>

And we are going to add a class which is defined in a CSS style property,


<style>
	.myClass {
		background-color: violet;
	}
</style>

And we have achieved it using the JQuery statement,


$('button').click( function() {
	$('p').addClass("myClass");
});

All we are doing is, using the addClass() method on the <p> element, to add the class 'myClass' to the <p> element.


$('p').addClass("myClass");

And we got the background-color of the <p> element as violet(Since violet is the 'background-color' defined in the class 'myClass').


Adding a class to multiple elements


Example :



<html>
    <head>
    	<title> My First Programme </title>
  	</head>

	<style>
    	.myClass {
        	background-color: violet;
        }
    </style>
    
  	<body>
    	<h1> JQuery </h1>
    	<p>New Code</p>
    	
    	<div> My div element </div>
    	
    	<button> Click Here </button>
    	
      	<script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script>
	  
      	<script>
      
      		$('button').click( function() {
				$('p, div').addClass("myClass");
			});
			
      	</script>      
   </body>
</html>


Output :




So, we can add a class to multiple elements using comma ','.

JQuery Method addClass()