Accessing and Modifying Styles

Contact Us or call 1-877-932-8228
Accessing and Modifying Styles

Accessing and Modifying Styles

The style object is a collection of an element's styles that are either defined within that HTML element's style attribute or directly in JavaScript. Styles defined in the <style> tag or in an external style sheet are not part of the style object.

The W3C specifies a method for getting at the current (or actual) style of an object: the window object's getComputedStyle() method, which is supported by most modern browsers, but not by Internet Explorer 6 and earlier. Internet Explorer provides a non-standard property for getting at the current style of an element: the currentStyle property.

Standard Syntax

window.getComputedStyle(Element, Pseudo-Element)

Note that the reference to window can be excluded as window is the implicit object. For example:

var div = document.getElementById("divTitle");
var curStyle = getComputedStyle(div, null);

Internet Explorer 6 Syntax


For example:

var div = document.getElementById("divTitle");
var curStyle = div.currentStyle;

Cross-browser Function

The following cross-browser function for getting the current value of a specific style property of an element is included in our lib.js file:

function getCurrentStyle(elem,property) {
	if (window.getComputedStyle) {
		var	computedStyle = getComputedStyle(elem,null);
		return computedStyle[property];
	} else if (elem.currentStyle) {
		return elem.currentStyle[property];

JavaScript style Properties

Each CSS property has a corresponding property of the JavaScript style object:

  • If the CSS property is a simple word (e.g, color) then the JavaScript property is the same (e.g, style.color).
  • If the CSS property has a dash in it (e.g, background-color) then the JavaScript property uses lower camel case (e.g, style.backgroundColor).