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

I'm changing CSS with jQuery and I wish to remove the styling I'm adding based on the input value:

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

How can I do this?
Note that the line above runs whenever a color is selected using a color picker (ie. when the mouse moves over a color wheel).

2nd note: I can't do this with css("background-color", "none") because it will remove the default styling from the CSS files.
I just want to remove the background-color inline style added by jQuery.

This question is related to javascript jquery css

The answer is


Try this:

$('#divID').css({"background":"none"});// remove existing

$('#divID').css({"background":"#bada55"});// add new color here.

Thanks


Try

document.body.style=''

_x000D_
_x000D_
$("body").css("background-color", 'red');

function clean() {
  document.body.style=''
}
_x000D_
body { background-color: yellow; }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="clean()">Remove style</button>
_x000D_
_x000D_
_x000D_


How about something like:

var myCss = $(element).attr('css');
myCss = myCss.replace('background-color: '+$(element).css('background-color')+';', '');
if(myCss == '') {
  $(element).removeAttr('css');
} else {
  $(element).attr('css', myCss);
}

This will remove complete tag :

  $("body").removeAttr("style");

I got the way to remove a style attribute with pure JavaScript just to let you know the way of pure JavaScript

var bodyStyle = document.body.style;
if (bodyStyle.removeAttribute)
    bodyStyle.removeAttribute('background-color');
else        
    bodyStyle.removeProperty('background-color');

This one also work!!

$elem.attr('style','');

Try This

$(".ClassName").css('color','');
Or 
$("#Idname").css('color','');

Why not make the style you wish to remove a CSS class? Now you can use: .removeClass(). This also opens up the possibility of using: .toggleClass()

(remove the class if it's present, and add it if it's not.)

Adding / removing a class is also less confusing to change / troubleshoot when dealing with layout issues (as opposed to trying to figure out why a particular style disappeared.)


The accepted answer works but leaves an empty style attribute on the DOM in my tests. No big deal, but this removes it all:

removeAttr( 'style' );

This assumes you want to remove all dynamic styling and return back to the stylesheet styling.


2018

there is native API for that

element.style.removeProperty(propery)

either of these jQuery functions should work:

$("#element").removeAttr("style");
$("#element").removeAttr("background-color") 

This is more complex than some other solutions, but may offer more flexibility in scenarios:

1) Make a class definition to isolate (encapsulate) the styling you want to apply/remove selectively. It can be empty (and for this case, probably should be):

.myColor {}

2) use this code, based on http://jsfiddle.net/kdp5V/167/ from this answer by gilly3:

function changeCSSRule(styleSelector,property,value) {
    for (var ssIdx = 0; ssIdx < document.styleSheets.length; ssIdx++) {
        var ss = document.styleSheets[ssIdx];
        var rules = ss.cssRules || ss.rules;
        if(rules){
            for (var ruleIdx = 0; ruleIdx < rules.length; ruleIdx++) {
                var rule = rules[ruleIdx];
                if (rule.selectorText == styleSelector) {
                    if(typeof value == 'undefined' || !value){
                        rule.style.removeProperty(property);
                    } else {
                        rule.style.setProperty(property,value);
                    }
                    return; // stops at FIRST occurrence of this styleSelector
                }
            }
        }
    }
}

Usage example: http://jsfiddle.net/qvkwhtow/

Caveats:

  • Not extensively tested.
  • Can't include !important or other directives in the new value. Any such existing directives will be lost through this manipulation.
  • Only changes first found occurrence of a styleSelector. Doesn't add or remove entire styles, but this could be done with something more elaborate.
  • Any invalid/unusable values will be ignored or throw error.
  • In Chrome (at least), non-local (as in cross-site) CSS rules are not exposed through document.styleSheets object, so this won't work on them. One would have to add a local overrides and manipulate that, keeping in mind the "first found" behavior of this code.
  • document.styleSheets is not particularly friendly to manipulation in general, don't expect this to work for aggressive use.

Isolating the styling this way is what CSS is all about, even if manipulating it isn't. Manipulating CSS rules is NOT what jQuery is all about, jQuery manipulates DOM elements, and uses CSS selectors to do it.


Just using:

$('.tag-class').removeAttr('style');

or

$('#tag-id').removeAttr('style');

You can use:

 $("#eslimi").removeAttr("style").hide();

let el = document.querySelector(element)
let styles = el.getAttribute('style')

el.setAttribute('style', styles.replace('width: 100%', ''))

Use my Plugin :

$.fn.removeCss=function(all){
        if(all===true){
            $(this).removeAttr('class');
        }
        return $(this).removeAttr('style')
    }

For your case ,Use it as following :

$(<mySelector>).removeCss();

or

$(<mySelector>).removeCss(false);

if you want to remove also CSS defined in its classes :

$(<mySelector>).removeCss(true);

If you use CSS style, you can use:

$("#element").css("background-color","none"); 

and then replace with:

$("#element").css("background-color", color);

If you don't use CSS style and you have attribute in HTML element, you can use:

$("#element").attr("style.background-color",color);

There are several ways to remove a CSS property using jQuery:

1. Setting the CSS property to its default (initial) value

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

See the initial value for the CSS property at MDN. Here the default value is transparent. You can also use inherit for several CSS properties to inherite the attribute from its parent. In CSS3/CSS4, you may also use initial, revert or unset but these keywords may have limited browser support.

2. Removing the CSS property

An empty string removes the CSS property, i.e.

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

But beware, as specified in jQuery .css() documentation, this removes the property but it has compatibilty issues with IE8 for certain CSS shorthand properties, including background.

Setting the value of a style property to an empty string — e.g. $('#mydiv').css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css() method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or element. Warning: one notable exception is that, for IE 8 and below, removing a shorthand property such as border or background will remove that style entirely from the element, regardless of what is set in a stylesheet or element.

3. Removing the whole style of the element

.removeAttr("style")

Simple is cheap in web development. I recommend using empty string when removing a particular style

$(element).style.attr = '  ';

you remove style using

removeAttr( 'style' );


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width