SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast
    Join Date
    Jul 2005
    Posts
    43
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Help: Get CSS properties from css-class?

    Hello,

    I need to get some properties from an element based on it's css-class, not it's style.

    for instance:

    HTML Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    	<style type="text/css">
    		.box {width:145px; height:300px; background-color:#bb0000; border:5px solid #990000;}
    	</style>
    </head>
    <body>
    	<div id="box" class="box"></div>
    	<button onclick="javascript:alert(document.getElementById('box').style.width);">Get Width</button>
    </body>
    </html>
    I would need the button above to return "145px".. but since it's not within a "style" attribute on the element, it won't return it. How can I get "145px" from the element through it's css-class. Note, javascript measuring, etc. won't work because the element might not be displayed on the screen, which is why it is imperative that it comes from the defined style.

    Thanks in advance for the help!

  2. #2
    SitePoint Wizard
    Join Date
    Nov 2004
    Location
    Nelson BC
    Posts
    2,310
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    In IE use currentStyle property

    in "other" browsers use getComputedStyle function

    PS - (Mike Foster rocks)
    http://cross-browser.com/x/lib/view....tcomputedstyle

  3. #3
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Jim, Thanks very much!

    Rege, Jim gave a good tip - here's another: xTraverseStyleSheet. It just depends on whether you want the computed value, or the literal value from the stylesheet rule. Here's an example of usage:
    Code:
    window.onload = function()
    {
      var ss = document.styleSheets[0];
      xTraverseStyleSheet(ss, ruleCallback);
    }
    function ruleCallback(r)
    {
      if (r.selectorText.indexOf('#de4') != -1) {
        alert(r.selectorText + ':\n' + r.style.background);
        return true;
      }
      return false;
    }


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •