View RSS Feed

jscheuer1

Get Style

Rate this Entry
Sometimes we want to get the style of something. But, since it wasn't set inline or via javascript, or perhaps was set in a stylesheet using the:

Code:
!important
keyword that overrides inline and javascript assignments, we cannot access it. Here is a fairly robust script that will allow us to do so in many cases:

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function getStyle(){
	return null;
}
if(document.getElementById){
	(function(){
		if(window.getComputedStyle){
			var hump = /([A-Z])/g;
			function toDash(a, b){return '-' + b.toLowerCase();};
			function decamel(str){return str.replace(hump, toDash);};
		} else {
			var dash = /-(.)/g;
			function toHump(a, b){return b.toUpperCase();};
			function encamel(str){return str.replace(dash, toHump);};
		}
		getStyle = (function(){
			return window.getComputedStyle? function(el, styleProp){
				return document.defaultView.getComputedStyle(el? document.getElementById(el)
				: document.body, null).getPropertyValue(decamel(styleProp));
			} : function(el, styleProp){return (el? document.getElementById(el)
				: document.body).currentStyle[encamel(styleProp)];};
		})();
	})();
}

onload = function(){alert(getStyle(null, 'background-color'));};
</script>
</head>
<body>
<div id="test">
Hi
</div>
</body>
</html>
You may pass it an element's id and property to get that element's style property value as currently viewed by the browser. Or, use null and a property to get the body's style property value for that property.

This works in IE 5.5+ and virtually all modern browsers.

You may use the hyphenated or the camel style notation for properties which require them. For properties that are bundled, like border, margin, etc. You may have to ask for specific components of those styles. For instance:

border-left-width

not just border or border-left.

If a property is undefined, you may get an empty string or 'undefined', or perhaps even some other 'falsey' value. It depends upon whether or not the browser sees the property as having a default value or not, and if not, how it chooses to express that. Pixels and other position/dimension units may be converted to other valid units representing the same position/dimension in some browsers, and color values may be expressed in any of their various equivalent values (text, hex, decimal). That depends upon the browser and sometimes how (if at all) the value was assigned.

For most things though, you will get what you expect. In other cases, some tweaking of the property asked for, and/or tweaking of the interpretation of the result may be required.

Submit "Get Style" to del.icio.us Submit "Get Style" to StumbleUpon Submit "Get Style" to Google Submit "Get Style" to Digg

Updated 03-05-2010 at 01:52 AM by jscheuer1 (precision in explanations)

Tags: None Add / Edit Tags
Categories
JavaScript & Ajax

Comments

  1. Nile's Avatar
    Very useful! Thank you!
  2. molendijk's Avatar
    This is simpler:
    Code:
    <head>
    
    <script type="text/javascript">
    function getStyle(el,styleProp)
    {
    	var x = document.getElementById(el);
    	if (x.currentStyle)
    		var y = x.currentStyle[styleProp];
    	else if (window.getComputedStyle)
    		var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
    	return y;
    }
    </script>
    
    </head>
    <body onclick=alert(getStyle('test','background-color'))>
    <div id="test" style="background:red"></div>
    so I suppose your script is more powerful?
    ===
    Arie Molendijk.
  3. jscheuer1's Avatar
    Hi Arie,

    The code is simpler, less efficient and less thourough though. I have the functions rewrite themselves during the initial parse. That way no branching is required for repeated executions. Also the code you post (taken pretty much verbatim from:

    http://www.quirksmode.org/dom/getstyles.html

    without credit on your part), has no mechanism to deal with hyphenated/camelBack styles cross browser. My method does.
  4. molendijk's Avatar
    OK, thanks.
    (I had the code somewhere without reference to the source. I should have verified that).
    ===
    Arie.