Explain Codes LogoExplain Codes Logo

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

javascript
jquery
css
javascript-best-practices
Alex KataevbyAlex Kataev·Dec 18, 2024
TLDR

To reset a specific CSS property set with jQuery's .css(), assign it an empty string ' ':

$('#element').css('property', '');

Remove all inline styles with .removeAttr():

$('#element').removeAttr('style');

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:

$('#element').css('background-color', ''); // Meet the old you, '#element'

If you wish for a complete makeover of the element to its original look, remove all inline styles using .removeAttr('style'):

$('#element').removeAttr('style'); // '#element' goes retro

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:

document.getElementById('element').removeAttribute('style'); // Yes, '#element', feel the freedom

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():

document.getElementById('element').style.removeProperty('background-color'); // Peel off the last layer, '#element'

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:

$('.color-picker').on('change', function() { $('#element').css('background-color', ''); // '#element', welcome your color-swap personality });

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:

if ($('#element').attr('style')) { $('#element').removeAttr('style'); // Double check before you wreck, '#element' }