The jQuery removeClass() method, as the name suggests, is used to remove one or more class names from a selector. For removing multiple class names, separate them using spaces.
$(selector).removeClass(classname,function(index,currentclass))
Parameter | Description |
---|---|
classname | Required Parameter: names of the classes to be removed from the selector. If more than one, use space to separate them. |
function(index,currentClass) | Optional Parameter: A function that returns one or more class names that are spaces-separated. The returned class names are removed from the selector.
|
I have a paragraph element that has a CSS Class called red.
<style>
.red {
color: Red;
}
</style>
<p id="myParagraph" class="red">My Paragraph</p>
<button id="myButton">Remove Class</button>
On the button Click I use jQuery removeClass for removing this ‘red’ class:
$("#myButton").click(function (e) {
$("#myParagraph").removeClass("red");
});
The above jQuery code will remove the red Class from the paragraph and it’s color changes to Green (which is the default color).
I can remove more than one class from the selector using jQuery removeClass method.
Here I remove 3 CSS Classes from the paragraph element. These classes are red, fontBold and borderSolid.
<style>
.red {
color: Red;
}
.fontBold {
font-weight: bold;
}
.borderSolid {
border: solid 1px #4CAF50;
}
</style>
<p id="myParagraph" class="red borderSolid fontBold">My Paragraph</p>
<button id="myButton">Remove 3 Class</button>
The jQuery code:
$("#myButton").click(function (e) {
$("#myParagraph").removeClass("red fontBold borderSolid");
});
In the above jQuery removeClass code I gave the three classes name separated by space.
So on the button click event the myParagraph element will lose it’s red, fontBold and borderSolid classes.
The class names returned by this function are removed from the selector.
I have 3 paragraph element, 2 have red and fontBold classes while the 3rd has fontBold class.
Now I want to remove red & borderSolid classes from these paragraphs.
<style>
.red {
color: Red;
}
.fontBold {
font-weight: bold;
}
.borderSolid {
border: solid 1px #4CAF50;
}
</style>
<p class="red borderSolid">First Paragraph with class "Red"</p>
<p class="red">Second Paragraph with class "Red"</p>
<p class="fontBold">Third Paragraph without any class</p>
<button id="myButton">Add Class</button>
The jQuery addClass code will be:
$("#myButton").click(function (e) {
$("p").removeClass(function (index, currentClass) {
return "red borderSolid";
});
});
I returned red borderSolid from the function and these 2 classes will be removed from the selector.
Check the download link:
Note: Obviously the 3rd paragraph which has the fontBold class remains unharmed.