shenkwen
shenkwen

Reputation: 3880

how do get CSS property value as in CSS files instead of computed ones?

When I inspect webpages and want to adjust elements whose font-size value are in percentage or em, I always have to go through their ancestors to find out on whom those percentage values are based on. Since this scenario happens a lot in my life, I am trying to write some code to make things easier. But the problem is, jQuery's .css() method is only getting computed values, like below.

  1. how do I get an element's exact CSS value as in CSS files or style tag?
  2. Is there any function which works like .offsetParent() and can achieve my original goal? EDIT: For clarification, I want to find the nearest ancestor whose font-size property is set in px. Like .offsetParent(), which can find the nearest ancestor that is 'positioned'.
  3. An off-topic question: in the fiddle below, why is the computed value 19.2000007629395 instead of 19.2 which equals to 16*120%?

jsfiddle: http://jsfiddle.net/yae8qn70/

HTML:

<div class='a'>
    <div class='b'>120% font</div>
</div>
Result:<span class='r'></span>

css:

.a{font-size:16px}
.b{font-size:120%}

Js:

$('.r').text($('.b').css('font-size'))

Upvotes: 0

Views: 78

Answers (2)

guest271314
guest271314

Reputation: 1

Try

$('.r').text(function (_, text) {

    var parent = window.getComputedStyle($('.b').parent()[0], null)
                 .getPropertyValue("font-size");

    var elem = window.getComputedStyle($('.b')[0], null)
               .getPropertyValue("font-size");

    var res = (Math.ceil((parseInt(elem) / parseInt(parent)) * 100));

    return res + "%"

});

jsfiddle http://jsfiddle.net/yae8qn70/1/

Upvotes: 0

Stephen Thomas
Stephen Thomas

Reputation: 14053

No easy method, I'm afraid, but if you're determined, you could do something like the following:

  1. Get the stylesheets using, e.g. var styleSheetList = document.styleSheets;
  2. Iterate through each one.
  3. For each style sheet, read the rules .cssRules
  4. Parse each rule in the array looking for the selector you want.

Obviously, you'll have to implement the CSS cascade in your code. Seems like an awful lot of work, but it's at least theoretically possible

Upvotes: 1

Related Questions