JavaScript get Styles
You are talking about what is known as Computed Style, check out these article on how to get it:
- Get Styles on QuirksMode
- Get Computed Style
- Get the rendered style of an element
From the last article, here is a function:
function getStyle(oElm, strCssRule){
var strValue = "";
if(document.defaultView && document.defaultView.getComputedStyle){
strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
}
else if(oElm.currentStyle){
strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
return p1.toUpperCase();
});
strValue = oElm.currentStyle[strCssRule];
}
return strValue;
}
How to use it:
CSS:
/* Element CSS*/
div#container{
font: 2em/2.25em Verdana, Geneva, Arial, Helvetica, sans-serif;
}
JS:
var elementFontSize = getStyle(document.getElementById("container"), "font-size");
You might use:
var ob = document.getElementById("myLayer");
var pos = ob.style.position;
Every CSS property has it's own object model. Usually those css properties that contain '-' are written using java model.
For example:
//getting background-color property
var ob = document.getElementById("myLayer");
var color = ob.style.backgroundColor;
If you want to get all the css properties that are defined for an object, you will have to list them one by one, because even if you did not set the property in your style sheet, an object will have it with the default value.
Polyfill to get the current CSS style of element using javascript ... Visit the link for more info
/**
* @desc : polyfill for getting the current CSS style of the element
* @param : elem - The Element for which to get the computed style.
* @param : prop - The Property for which to get the value
* @returns : The returned style value of the element
**/
var getCurrentStyle = function (ele, prop) {
var currStyle;
if (!window.getComputedStyle) {
currStyle = ele.currentStyle[prop];
} else {
currStyle = window.getComputedStyle(ele).getPropertyValue(prop);
}
return currStyle;
}
/** How to use **/
var element = document.getElementById("myElement");
getCurrentStyle(element, "width"); // returns the width value