Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
150
rated 0 times [  157] [ 7]  / answers: 1 / hits: 16539  / 14 Years ago, sat, november 13, 2010, 12:00:00

Is it possible to get ALL of the styles for an object using JavaScript? Something like:





main.css
-------
#myLayer {
position: absolute;
width: 200px;
height: 100px;
color: #0000ff;
}

main.js
-------
var ob = document.getElementById(myLayer);
var pos = ob.(getPosition);
// Pos should equal absolute but
// ob.style.position would equal null
// any way to get absolute?



More From » css

 Answers
12

You are talking about what is known as Computed Style, check out these article on how to get it:





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);

[#94972] Thursday, November 11, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryankiah

Total Points: 183
Total Questions: 99
Total Answers: 112

Location: Christmas Island
Member since Mon, Oct 19, 2020
4 Years ago
;