The .css()
method can remove inline styles (denoted by style=""
):
var target = document.getElementById('target');
$('#target').css('color', '');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="target" style="color: red">Target</div>
But not styling rules that have been defined in a CSS stylesheet:
var target = document.getElementById('target');
$('#target').css('color', '');
#target {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="target">Target</div>
Nor will it work for styling inside <style>
tags written in the same file:
var target = document.getElementById('target');
$('#target').css('color', '');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="target">Target</div>
<style>
#target {
color: red;
}
</style>
This is because the CSSStyleDeclaration object is a read-only interface to Window.GetComputedStyle()
, which is used to retrieve the stylesheets.
The Window.getComputedStyle()
method returns an object that reports the values of all CSS properties of an element after applying active stylesheets and resolving any basic computation those values may contain.
Element.style
returns a CSSStyleDeclaration
object, and is also read-only:
Styles should not be set by assigning a string directly to the style property (as in elt.style = "color: blue;"
), since it is considered read-only, as the style attribute returns a CSSStyleDeclaration object which is also read-only.
jQuery's css()
method itself attempts to modify the style property, and thus it can only update inline styles:
When using .css()
as a setter, jQuery modifies the element's style property. [ ... ] 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.