The addClass() method in JQuery is used to insert a CSS class to an element/elements.
<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>
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').
<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>
So, we can add a class to multiple elements using comma ','.