How can I remove a style added with .css() function?
To reset a specific CSS property set with jQuery's .css()
, assign it an empty string ' '
:
Remove all inline styles with .removeAttr()
:
jQuery .css() function 101
While using jQuery's .css()
function, you're directly applying inline styling, not to be confused with the styles provided by external stylesheets.
Resetting a style property to an empty string allows you to boldly send a style property back to its default value in your stylesheet like so:
If you wish for a complete makeover of the element to its original look, remove all inline styles using .removeAttr('style')
:
Compatibility Backwards and Forwards
Maintaining browser compatibility is as important as mastering jQuery, because old-timers like IE8 may not always like empty strings as CSS property values.
Also, there's no harm in doing it the old school JavaScript way:
This is equivalent to the the jQuery way of .removeAttr('style')
, removing all inline stylings at once.
And to remove just one specific property in pure JavaScript, use removeProperty()
:
Dynamic Styles and Color Pickers
Styles can change dynamically. Example: a color picker. So you've got to make sure that your code runs automatically upon color selection. Removing a specific style becomes key here:
Keeping Integrity with Default Styles
Attempting to maintain the integrity of your style whenever you remove a style is very important. It's like removing one card from your house of cards. It should not affect the entire structure! This is how you can check before you leap:
Was this article helpful?