W3cubDocs

/DOM

HTMLElement.style

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

Styles can be set by assigning a string directly to the style property (as in elt.style = "color: blue;" ),which forwards it as el.style.cssText = "color:blue;" , though it returns a CSSStyleDeclaration object which is 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

var div = document.getElementById("div1");
div.style.marginTop = ".25in";

The following code displays the names of all the style properties, the values set explicitly for element elt and the inherited 'computed' values:

var element = document.getElementById("elementIdHere");
var out = "";
var elementStyle = element.style;
var computedStyle = window.getComputedStyle(element, null);

for (prop in elementStyle) {
  if (elementStyle.hasOwnProperty(prop)) {
    out += "  " + prop + " = '" + elementStyle[prop] + "' > '" + computedStyle[prop] + "'\n";
  }
}
console.log(out)

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';

See also

© 2005–2017 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style