Our volunteers haven't translated this article into عربي yet. Join us and help get the job done!
Summary
The HTMLElement.style
property returns a CSSStyleDeclaration
object that represents only the element's inline style
attribute, ignoring any applied style rules. See the CSS Properties Reference for a list of the CSS properties accessible via style
.
Since the style
property has the same (and highest) priority in the CSS cascade as an inline style declaration via the style
attribute, it is useful for setting style on one specific element.
Setting style
Note that 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 (even though Firefox(Gecko), Chrome and Opera allow it) because the style attribute returns a CSSStyleDeclaration
object which is also read-only. However, the style
property's own properties CAN be used to set styles. Further, it is easier to use the individual styling-properties of the style
property (as in elt.style.color = '...'
) than to use elt.style.cssText = '...' or elt.setAttribute('style', '...')
, unless you wish to set the complete style in a single statement, since using the style
properties will not overwrite other CSS properties that may already be set in the style
attribute.
Examples
elt.style.cssText = "color: blue"; // Multiple style properties
elt.setAttribute("style", "color: blue"); // Multiple style properties
elt.style.color = "blue"; // Directly
var st = elt.style;
st.color = "blue"; // Indirectly
Getting style information
The style
property is not useful for learning about the element's style in general, since it represents only the CSS declarations set in the element's inline style
attribute, not those that come from style rules elsewhere, such as style rules in the <head>
section, or external style sheets. To get the values of all CSS properties for an element you should use window.getComputedStyle()
instead.
Example
The following code displays the names of all the style properties, the values set explicitly for element elt
and the inherited 'computed' values:
var elt = document.getElementById("elementIdHere"); var out = ""; var st = elt.style; var cs = window.getComputedStyle(elt, null); for (x in st) { out += " " + x + " = '" + st[x] + "' > '" + cs[x] + "'\n"; }
Specification
DOM Level 2 Style: ElementCSSInlineStyle.style
Compatibility
Note: Starting in Gecko 2.0, you can set SVG properties' values using the same shorthand syntax. For example:
element.style.fill = 'lime';