DOM:element.style
From MDC
Contents |
[edit] Summary
Returns an object that represents the element's style attribute.
[edit] Example
var div = document.getElementById("div1");
div.style.marginTop = ".25in";
[edit] Notes
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.
However, it 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.
See the DOM CSS Properties List for a list of the CSS properties that are accessible from the Gecko DOM. There are some additional notes there about the use of the style property to style elements in the DOM.
It is generally better to use the style property than to use elt.setAttribute('style', '...'), since use of the style property will not overwrite other CSS properties that may be specified in the style attribute.
Styles can not be set by assigning a string to the (read only) style property, as in elt.style = "color: blue;". This is because the style attribute returns a CSSStyleDeclaration object. Instead, you can set style properties like this:
elt.style.color = "blue"; // Directly var st = elt.style; st.color = "blue"; // Indirectly
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";