How to Remove Style Added with the .css() function Using jQuery
Read this tutorial and learn several ways of removing style added with the .css() function with the help of jQuery. Choose the best method for your case.
You can remove styles added using both JavaScript and jQuery. However, in this tutorial, we suggest jQuery methods that require lesser code.
Let’s discuss the following scenario:
Scenario: Removing a Dynamically Added Style
if (color !== '#ffffff') {
$("body").css("background-color", color);
} else {
// How to remove the style?
}Method 1: Resetting a Specific Property
Passing an empty string resets the targeted CSS property to its default value:
$("selector").css("background-color", "");For properties like width or height, you can also use .css('property', 'auto') to reset them to their natural size. Avoid using "none" for properties like background-color, as it is often invalid and won't revert to the default stylesheet value.
Method 2: Removing the Entire Style Attribute
You can also remove all inline styles at once using the jQuery <kbd class="highlighted">removeAttr()</kbd> method:
$("selector").removeAttr('style');Be careful when using removeAttr('style'), as it removes the entire style attribute, including any other inline styles applied to the element.
Complete Example
<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
</head>
<body>
<h1 style="color:red">Red text </h1>
<button>Remove</button>
<script>
$(document).ready(function() {
$("button").click(function() {
$("h1").removeAttr("style");
});
});
</script>
</body>
</html>The css() and removeAttr() Methods
The <kbd class="highlighted">.css()</kbd> jQuery method is used to set or return one or more style properties for the selected elements.
The <kbd class="highlighted">.removeAttr()</kbd> jQuery method removes an attribute from each element in the collection of matched elements. The method uses the JavaScript <kbd class="highlighted">removeAttribute()</kbd> function, but it is capable of being called directly on a jQuery object.