How to Remove All Classes Using jQuery
When manipulating web page styling dynamically, you may need to strip
an element of every applied CSS class at once. jQuery provides multiple
simple, built-in methods to accomplish this, such as calling
.removeClass() without arguments or clearing the attribute
with .removeAttr(). This guide explains the most effective
techniques to remove all CSS classes from an HTML element using
jQuery.
Method 1: Using
.removeClass() (Recommended)
The most idiomatic and readable way to clear all classes in jQuery is
calling the .removeClass() method without passing any
parameters.
$('#myElement').removeClass();When called with no arguments, .removeClass()
automatically removes all assigned class names from the matched
elements.
Example:
<div id="box" class="card shadow rounded p-4 text-center">Content</div>
<script>
// Removes "card", "shadow", "rounded", "p-4", and "text-center"
$('#box').removeClass();
</script>Method 2: Using
.removeAttr('class')
Another common approach is completely removing the class
attribute from the element's DOM node using
.removeAttr().
$('#myElement').removeAttr('class');Unlike .removeClass(), which clears the class names
while sometimes leaving an empty class="" attribute in the
DOM depending on the browser, .removeAttr('class') strips
the entire attribute from the tag.
Resulting HTML:
<!-- Before -->
<div id="box" class="btn btn-primary">Button</div>
<!-- After $('#box').removeAttr('class'); -->
<div id="box">Button</div>Method 3: Using
.attr('class', '')
You can also set the value of the class attribute to an
empty string.
$('#myElement').attr('class', '');This clears the styles associated with the classes, leaving an empty
class="" attribute on the element.
Summary: Which Method Should You Use?
- Use
$('#element').removeClass()for standard jQuery code. It is clear, intuitive, and the official way to reset element classes. - Use
$('#element').removeAttr('class')if your goal is to keep the DOM clean by deleting theclassattribute entirely.