Can't Access CSS Selector's Properties from Javascript
css, html, javascript
Solution
You can get the values set through class only after their computation.
var oElm = document.getElementById ( "myStyle" );
var strValue = "";
if(document.defaultView && document.defaultView.getComputedStyle)
{
strValue = document.defaultView.getComputedStyle(oElm, null).getPropertyValue("-moz-opacity");
}
else if(oElm.currentStyle) // For IE
{
strValue = oElm.currentStyle["opacity"];
}
alert ( strValue );
Problem
Here's a very basic question: why is the finishLoading() function in the code below not able to access the 'opacity' property for the #myStyle CSS selector? The alert doesn't display anything, and I've verified that the 'opacity' property is 'false'. Thanks very much! ``` <html> <head> <style type="text/css"> <!-- #myStyle { opacity: 0.50; } --> </style> <script type="text/javascript"> <!-- function finishedLoading() { alert(document.getElementById('myStyle').style.opacity); } --> </script> </head> <body onload="finishedLoading();"> <div id="myStyle"> hello </div> </body> </html> ```