Home / DHTML & CSS / Getting global and external style sheet values in DHTML


 

CodingForums
Having trouble with scripting? Visit our help forum to get the answers you need.

Jump to...
-Free JavaScripts
-JS tutorials
-JS Reference
-DHTML/CSS

-Free applets
-Web Tutorials
-Link to Us!


Getting global and external style sheet values in NS6+

In NS6, getting the property values of global/external style sheets is slightly more cumbersome, and involves 2 steps:

1) Use window.getComputedStyle() to first retrieve the style settings of the element in question.
2) Then, use getPropertyValue() on top of it to retrieve the value of the desired CSS property value.

Lets jump straight to an example, which is probably the quickest way to illustrate how the technique works:

<head>
<style type="text/css">
#test{
width: 100px;
height: 80px;
background-color: yellow;
}
</style>
</head>

<body>
<div id="test">This is some text</div>

<script type="text/javascript">
var mydiv=document.getElementById("test")
var mydivstyle=window.getComputedStyle(mydiv, "")
var divwidth=mydivstyle.getPropertyValue("width") //contains "100px"
var divbgcolor=mydivstyle.getPropertyValue("background-color") //contains "yellow"
</script>
</body>

I first use window.getComputedStyle() to retrieve the current style settings of an element, in this case, our lovely DIV (second parameter is fed an empty string). Then, the method getPropertyValue() is invoked on it to get a specific property value within it. Note that the original, unaltered CSS property name should be used instead of contracting the hyphen in cases where applicable (ie: background-color versus backgroundColor). This differs from IE's currentStyle() method, which requires the familiar contraction.

-Tutorial introduction
-Getting global and external style sheet values in IE5+
-Getting global and external style sheet values in NS6+
-Cross browser function for retrieving global/external CSS properties

Cross browser function for retrieving global/external CSS properties

http://www.javascriptkit.com
Copyright © 1997-2005 JavaScript Kit. NO PART may be reproduced without author's permission.