Goose Posted June 12, 2007 Share Posted June 12, 2007 I am writing some JavaScript code where I need to get CSS style attributes. However, I am running into a problem where I cannot access style attributes that aren't defined in the declaration of the object. In the following example I cannot get the height of testA because the height is defined within a style sheet where as I can get the height of testB because it is defined in the style attribute of the div. <html> <head> <style type="text/css"> #testA{ height: 100px; background-color: #c0c0c0; } #testB{ background-color: #e0e0e0; } </style> <script type="text/javascript"> function getHeight(element){ alert(element.style.height); } </script> </head> <body> <div id="testA" onclick="getHeight(this);"> Test A -- If you click this div it doesn't return the object height. </div> <div id="testB" onclick="getHeight(this);" style="height: 100px;"> Test B -- If you click this div it does return the object height. </div> </body> </html> Any ideas would be great ... I hate this problem. Thanks in advance. Link to comment https://forums.phpfreaks.com/topic/55190-javascript-accessing-css-style-attributes/ Share on other sites More sharing options...
nogray Posted June 12, 2007 Share Posted June 12, 2007 Try to use the NoGray javascript library, there is a getStyle function that will return the current style of the object. Since the documentations are a bit outdated, here is a quick example <html> <head> <title>getStyle Example</title> <!-- including the base.js --> <script language="javascript" src="nogray_lib/base.js" type="text/javascript"></script> <script language="javascript"> function ini_page(){ // this function will assign the NoGray libraray methods // to the object // _obj() is the same as document.getElementById() make_NoGray(_obj('wdiv')); // getting the style attributes // you need to use a full attribute for example // backgroundColor rather than background var txt = "Background color: "+_obj('wdiv').getStyle("backgroundColor")+"\n"; txt += "Font family: "+_obj('wdiv').getStyle("fontFamily")+"\n"; txt += "Height: "+_obj('wdiv').getHeight()+"\n"; txt += "Width: "+_obj('wdiv').getWidth(); alert(txt); } </script> </head> <body onLoad="ini_page();"> <div id="wdiv">Hello World</div> </body> </html> Link to comment https://forums.phpfreaks.com/topic/55190-javascript-accessing-css-style-attributes/#findComment-273287 Share on other sites More sharing options...
Goose Posted June 12, 2007 Author Share Posted June 12, 2007 Awesome!!! Thanks nogray! Link to comment https://forums.phpfreaks.com/topic/55190-javascript-accessing-css-style-attributes/#findComment-273483 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.