1

I need a technique to get the value from a CSS file through a javascript function.

Here is the sample of my code:
HTML file ->

    <link rel="stylesheet" type="text/css" href="test_css.css" />
    <script type="text/javascript">
    function loadFunc(){ 
    ## code needed here
    ## alert(left);
    }
    </script>

CSS file ->

    .outer .inner
    {
    left: 30pt;
    top: 20pt;
    }

Note: I don't need the whole CSS Text. I want only the property value mentioned for a partuclar key. Is is possible to achieve this using any predefined function?

For example I need the value mentioned for the key - "left" in the CSS file. The result should be "30pt".

pragaas
  • 43
  • 4
  • 3
    This should do it: http://stackoverflow.com/questions/16965515/how-to-get-a-style-attribute-from-a-css-class-by-javascript-jquery – Daniel Szabo Nov 20 '13 at 04:14

2 Answers2

0

Calling this function with the required attributes would return the desired value.

    function getStyleRuleValue(style, selector, sheet) {
      var sheets = typeof sheet !== 'undefined' ? [sheet] : document.styleSheets;
      for (var i = 0, l = sheets.length; i < l; i++) {
        var sheet = sheets[i];
        if( !sheet.cssRules ) { continue; }
        for (var j = 0, k = sheet.cssRules.length; j < k; j++) {
          var rule = sheet.cssRules[j];
          if (rule.selectorText && rule.selectorText.split(',').indexOf(selector) !== -1) 
             return rule.style[style];            
         }
       }
      return null;
     }

    var color = getStyleRuleValue('top', '.classproperty'); // for all the sheets
pragaas
  • 43
  • 4
-1

Use jQuery and the .css function. More info: http://api.jquery.com/css/

Edit: this assumes you have the style somewhere visible on the page. If you don't, well you could create a hidden div that the css selector will apply to.

Some Guy
  • 12,768
  • 22
  • 58
  • 86
  • The OP never asked for jQuery – Zach Saucier Nov 20 '13 at 04:24
  • He also didn't say he doesn't want to use any library. – Some Guy Nov 20 '13 at 04:26
  • You can compare what you're attempting to give the OP to giving someone a whole physical library when all they need is a book. True, they could use the library and find what they need, but there is a lot of extra hassle involved. It'd be better to just provide what they need (the particular book) and asked for – Zach Saucier Nov 20 '13 at 04:35
  • I dont need a jQuery. Sorry, forgot to specify. – pragaas Nov 20 '13 at 06:07
  • As another analogy, it could be someone who doesn't know about calculators trying to do a large long division by hand. They ask you for help, and you give them a calculator. Without any knowledge of whether the OP is a novice or an expert who consciously is choosing to not use a framework like jQuery, it's better IMO to mention jQuery. I'd have wanted to know if there was a tool that would save me time. – Some Guy Nov 30 '13 at 22:14