$style – Get Any CSS Property Value of an Object

HTML5, CSS3 and JavaScript

The Fine Art of Web Development by Martin Ivanov

Here is a crossbrowser JavaScript function for getting CSS property values from DOM elements. The function $style requires the specification of two arguments:

$style(ElementId, CssProperty);

ElementId – the ID of the element from which we will extract CSS property values;
CssProperty – the CSS property we will extract from the element, for example – “background-color”;

The function $style:

function $style(ElementId, CssProperty)
function $(stringId)
return document.getElementById(stringId);
var convertToCamelCase = CssProperty.replace(/-(.)/g, function(m, l){return l.toUpperCase()});
return $(ElementId).currentStyle[convertToCamelCase];
else if (window.getComputedStyle)
var elementStyle = window.getComputedStyle($(ElementId), “”);
return elementStyle.getPropertyValue(CssProperty);

Example usage of the function:

1. Register the runtime routine of the $style in the <head>…</head>of your webpage, or as an external script.

2. The CSS for the example:

<style type=”text/css”>
border: solid 1px red;
background: #00ff00;
color: #000;
font-family: “Trebuchet MS”, Arial, Verdana;

2. The HTML for the example:

<div id=”Div1″>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Cras purus pede, aliquam vel, eleifend in, mollis sit amet, ante.</div>

3. The JavaScript for the example:

<script type=”text/javascript”>
function getElementStyles()
var elBgColor = $style(“Div1”, “background-color”);
var elForeColor = $style(“Div1”, “color”);
var elFont = $style(“Div1”, “font-family”);

alert(‘”Div1″ style settings:nnbackground color: ‘ + elBgColor + ‘;n’ + ‘color: ‘ + elForeColor + ‘;n’ + ‘font-family: ‘ + elFont + ‘;’);

4. And finally, you need an event to fire function. It could be any DOM event. For this example I have used the click event of a button:

<input type=”button” onclick=”getElementStyles()” value=”Get Element Styles” />

This script is included in the latest version of Acid.JS – The AJAX Tools and Widgets Library as well.

Categories and Tags

© 2006 - 2024 Martin Ivanov