jQuery CSS Classes
Using the jQuery CSS classes, it is easy to manipulate the CSS of elements. jQuery has several methods for CSS manipulation. These are as follows:
addClass() removeClass() toggleClass() css()
jQuery addClass() Method
jQuery addClass() method is used to add class attributes to different elements. This method is only used to add the class name to the class elements not to remove the attributes of the existing class. Syntax:$(selector).addClass(classname,function(index,currentclass))
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").addClass("intro");
});
});
</script>
<style>
.intro {
font-size: 200%;
color: red;
}
</style>
</head>
<body>
<h1>This is the first heading</h1>
<p>Hello, world!.</p>
<p>This is a paragraph.</p>
<button>Add a class name to the first p element</button>
</body>
</html>
jQuery removeClass() Method
jQuery remove() method is used to remove one or more classes from the selected elements. Syntax:$(selector).removeClass(classname,function(index,currentclass))
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("h2, p").removeClass("blue");
});
});
</script>
<style>
.important {
font-weight: bold;
font-size: xx-large;
}
.blue {
color: blue;
}
</style>
</head>
<body>
<h2 class="blue">This is a heading</h2>
<p class="blue">Hello, World!.</p>
<p>This is the a paragraph.</p>
<button>Remove class from elements</button>
</body>
</html>
jQuery toggleClass()
Using the jQuery toggleClass() method you can add or remove the classes from the selected elements. In this method, if the name of the class is missing, it adds or if the class name is already set, it removes. Syntax$(selector).toggleClass(classname,function(index,currentclass),switch)
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("h1, h2, p").toggleClass("red");
});
});
</script>
<style>
.red {
color: red;
}
</style>
</head>
<body>
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Toggle class</button>
</body>
</html>