Home »
jQuery »
jQuery Examples
How to remove multiple CSS classes using jQuery?
Learn, how can we remove some of the CSS styling classes from the elements using jQuery?
Submitted by Pratishtha Saxena, on September 07, 2022
Prerequisite: Adding jQuery to Your Web Pages
CSS can be added to an HTML page using different ways. One way of adding CSS is by defining it in the same tag where it has to be added. This is called inline CSS. Another way is by declaring the <style> tag in the head and defining all the CSS styling by classes, ids, and tag names. This is called internal CSS. The last way is by creating a new file with the ".css" extension and defining everything over there, and then link that file to the HTML page. This is termed external CSS.
This styling of the webpage using CSS classes can be handled using jQuery also. Some changes can be made to these classes, also if one wants to remove the CSS completely then that can also be achieved.
Remove single CSS class
Using .removeClass() method of jQuery, CSS classes can easily be removed if needed. This method only works on the classes that are specified in the style tag (<style>). It does help to remove the styles that are defined within the element, i.e., it does not work for inline CSS.
Syntax:
$('selector').removeClass('property', 'value');
Remove multiple CSS classes
To remove a specific property from the class specified in the selector, the above format is used. But it can also remove the complete class if nothing is passed as its parameters.
When multiple classes have to be removed then the name of the classes have to be mentioned with spaces in between. It will help to remove the classes that you wish to be removed from a particular element.
Syntax:
$('selector').removeClass('classOne classTwo classThree…');
Have a look at the following example for the same. Amongst the three classes defined, two of them have been removed using .removeClass() method.
jQuery example to remove multiple CSS classes
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>Document</title>
<style>
.style1{
font-size: 30px;
font-weight: 600;
}
.style2{
background-color: cadetblue;
}
.style3{
color: bisque;
}
</style>
</head>
<body>
<h2 id="myH">Remove Multiple CSS Classes Using jQuery</h2>
<p id="myPara">Click the button to some of the CSS from the following element.</p>
<div id="myDiv" class="style1 style2 style3">This is the Element with the CSS properties.</div>
<br><br>
<button type="button" id="button1" class="button">Remove CSS</button>
</body>
<script type="text/javascript">
$(document).ready(function(){
$('#button1').click(function(){
$('div').removeClass('style2 style3');
});
});
</script>
</html>
Output: