How to Remove Style Added with the .css() function Using jQuery

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:

if (color != 'ffffff') $("body").css("background-color", color);
else // remove style ?

Now let’s remove styling. An empty string will remove the CSS color property:

.css("background-color", "");

Don’t do css("background-color", "none") as it will remove the default styling from the css files.

There is another way to remove style. Simply use jQuery removeAttr() method:

removeAttr('style');
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>
Be careful because the following method removes all other properties in the style attribute.

The css() and removeAttr() Methods

The .css() jQuery method is used to set or return one or more style properties for the selected elements.

The .removeAttr() jQuery method removes an attribute from each element in the collection of matched elements.The method uses the JavaScript removeAttribute() function, but it is capable of being called directly on a jQuery object.

Do you find this helpful?

Related articles