Logo

How can I remove a style added with .css() function?

To remove a style previously applied via .css() in jQuery, set the property value to an empty string or remove the entire style attribute. For example:

// Remove a specific property: $("element").css("color", ""); // Remove all inline styles: $("element").removeAttr("style");

Detailed Explanation

1. Removing a Specific Property

If you only want to revert one property (or a few properties) to their default, set each property to an empty string:

$("element").css("background-color", ""); $("element").css("font-size", "");
  • Why it works: Setting a property to an empty string effectively removes that inline CSS property from the style attribute, letting any stylesheet or default browser style take precedence again.

2. Removing All Inline Styles

If you want to clear every inline style at once:

$("element").removeAttr("style");
  • Effect: The entire style="..." attribute is removed. Any styles from external or internal stylesheets still apply, but all inline styles are wiped out.

3. When to Use Each Approach

  1. Single/Multiple Properties: Use the “empty string” method if you only need to revert a handful of properties:

    // Only remove background color $(".box").css("background-color", "");
  2. All Inline Styles: Use .removeAttr("style") if you need a “clean slate,” removing everything set inline:

    // Remove all inline styles from an element $(".box").removeAttr("style");

4. Considerations

  • Specificity: If a stylesheet or other inline styles are applied later, they may override these changes.
  • Performance: If you’re toggling or often removing styles, consider using classes (.addClass(), .removeClass()) to manage style changes instead. This keeps your code more organized and typically performs better.

Key Takeaway
To remove a style from an element that was added with .css() in jQuery, either set that property’s value to "" or remove the entire style attribute for a complete reset of inline styles.

CONTRIBUTOR
TechGrind