Get Style
by
, 03-04-2010 at 02:37 PM (46431 Views)
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:
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:!important
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.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>
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.