Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > HTML > Re: Accessing style properties within JavaScript

Thread Tools

Re: Accessing style properties within JavaScript

Lasse Reichstein Nielsen
Posts: n/a
      08-07-2003 Removed) ((E-Mail Removed)) writes:

> Is it possible to access a particular property of a style rule without
> reference to an element that uses the rule?

In some browsers. See below.

> The hack I have tried is this: create a dummy element and set its
> class to match a style rule and then access the style property.
> However, I have found that my test for this does not work (code
> below).

It won't work, because the style property of the element does not
reflect the style that affects the element, but just the value of the
HTML style attribute of the element.
That is, if you have
<style type="text/css">
#foo {background-color:red;}
<div id="foo" style="color:yellow">BAR</div>
The the following code
var elemStyle = document.getElementById("foo").style;
alert(elemStyle.color + "/" + elemStyle.backgroundColor);
will alert the string "yellow/", because the color is given in the
style attribute and therefore is a property og the style object,
but the background color is not.

What you *can* do is one of two things.

1: to access the stylesheet element itself.
IE: alert(document.styleSheets[0].rules[0].style.backgroundColor);
Mozilla: alert(document.styleSheets[0].cssRules[0].style.backgroundColor);

This sounds as what you are asking for.

2: To access the computed style of the element, which is the collected
information from alls stylesheets and styles that affect the element.

IE: alert(document.getElementById("foo").currentStyle. backgroundColor);

Mozilla/Opera7.2(currently in beta):
var elem = document.getElementById("foo");
alert(document.defaultView.getComputedStyle(elem,n ull).backgroundColor)

I have made an example:
You can test it in IE, Mozilla and Opera 7.2beta2.
Lasse Reichstein Nielsen - (E-Mail Removed)
Art D'HTML: <URL:>
'Faith without judgement merely degrades the spirit divine.'
Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Accessing Datagrid properties within a user control from the outside Craig G ASP .Net 3 11-30-2004 02:51 PM
Need help with Style conversion from Style object to Style key/value collection. Ken Varn ASP .Net Building Controls 0 04-26-2004 07:06 PM
Style sheets, include one style within another (not inheritance) HTML 1 11-24-2003 01:37 PM
Re: Accessing style properties within JavaScript Keith Bowes HTML 0 08-07-2003 08:28 AM
Re: Accessing style properties within JavaScript e n | c k m a HTML 0 08-07-2003 07:23 AM