Re: Accessing style properties within JavaScript

Discussion in 'HTML' started by Lasse Reichstein Nielsen, Aug 7, 2003.

  1. () 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;}
    </style>
    ---
    and
    ---
    <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);
    or
    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,null).backgroundColor)


    I have made an example:
    <URL:http://www.infimum.dk/privat/stylesheets.html>
    You can test it in IE, Mozilla and Opera 7.2beta2.
    /L
    --
    Lasse Reichstein Nielsen -
    Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
    'Faith without judgement merely degrades the spirit divine.'
    Lasse Reichstein Nielsen, Aug 7, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Craig G
    Replies:
    3
    Views:
    726
    Craig G
    Nov 30, 2004
  2. e n | c k m a
    Replies:
    0
    Views:
    369
    e n | c k m a
    Aug 7, 2003
  3. Keith Bowes
    Replies:
    0
    Views:
    371
    Keith Bowes
    Aug 7, 2003
  4. Ken Varn
    Replies:
    0
    Views:
    443
    Ken Varn
    Apr 26, 2004
  5. Replies:
    2
    Views:
    76
Loading...

Share This Page