get CSS rule's percentage value in jQuery

JqueryCss

Jquery Problem Overview


Let's say the rule is as follows:

.largeField {
    width: 65%;
}

Is there a way to get '65%' back somehow, and not the pixel value?

Thanks.

EDIT: Unfortunately using DOM methods is unreliable in my case, as I have a stylesheet which imports other stylesheets, and as a result the cssRules parameter ends up with either null or undefined value.

This approach, however, would work in most straightforward cases (one stylesheet, multiple separate stylesheet declarations inside the head tag of the document).

Jquery Solutions


Solution 1 - Jquery

Most easy way

$('.largeField')[0].style.width

// >>> "65%"

Solution 2 - Jquery

This is most definitely possible!

You must first hide() the parent element. This will prevent JavaScript from calculating pixels for the child element.

$('.parent').hide();
var width = $('.child').width();
$('.parent').show();
alert(width);

See my example.

Now... I wonder if I'm first to discover this hack:)

Update:

One-liner

element.clone().appendTo('body').wrap('<div style="display: none"></div>').css('width');

It will leave behind a hidden element before the </body> tag, which you may want to .remove().

See an example of one-liner.

I'm open to better ideas!

Solution 3 - Jquery

There's no built-in way, I'm afraid. You can do something like this:

var width = ( 100 * parseFloat($('.largeField').css('width')) / parseFloat($('.largeField').parent().css('width')) ) + '%';

Solution 4 - Jquery

You could access the document.styleSheets object:

<style type="text/css">
    .largeField {
        width: 65%;
    }
</style>
<script type="text/javascript">
    var rules = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
    for (var i=0; i < rules.length; i++) {
        var rule = rules[i];
        if (rule.selectorText.toLowerCase() == ".largefield") {
            alert(rule.style.getPropertyValue("width"));
        }
    }
</script>

Solution 5 - Jquery

Late, but for newer users, try this if the css style contains a percentage:

$element.prop('style')['width'];

Solution 6 - Jquery

A jQuery plugin based on Adams answer:

(function ($) {

    $.fn.getWidthInPercent = function () {
        var width = parseFloat($(this).css('width'))/parseFloat($(this).parent().css('width'));
        return Math.round(100*width)+'%';
    };

})(jQuery);

$('body').html($('.largeField').getWidthInPercent());​​​​​

Will return '65%'. Only returns rounded numbers to work better if you do like if (width=='65%'). If you would have used Adams answer directly, that hadn't worked (I got something like 64.93288590604027). :)

Solution 7 - Jquery

Building on timofey's excellent and surprising solution, here is a pure Javascript implementation:

function cssDimensions(element) {
  var cn = element.cloneNode();
  var div = document.createElement('div');
  div.appendChild(cn);
  div.style.display = 'none';
  document.body.appendChild(div);
  var cs = window.getComputedStyle
    ? getComputedStyle(cn, null)
    : cn.currentStyle;
  var ret = { width: cs.width, height: cs.height };
  document.body.removeChild(div);
  return ret;
}

Hope it's helpful to someone.

Solution 8 - Jquery

I have a similar issue in https://stackoverflow.com/questions/7131462/getting-values-of-global-stylesheet-in-jquery, eventually I came up with the same solution as above.

Just wanted to crosslink the two questions so others can benefit from later findings.

Solution 9 - Jquery

Convert from pixels to percentage using cross multiplication.

Formula Setup:

1.) (element_width_pixels/parent_width_pixels) = (element_width_percentage / 100)

2.) element_width_percentage = (100 * element_width_pixels) / parent_width_pixels

The actual code:

<script>
   
   var $width_percentage = (100 * $("#child").width()) / $("#parent").width();

</script>

Solution 10 - Jquery

A late response but wanted to add on for anyone 2020+ who stumbles across this. Might be more for niche cases but I wanted to share a couple options.

If you know what the initial % value is you can also assign these values to variables in the :root of the style sheet. i.e

:root {
    --large-field-width: 65%;
}

.largeField {
  width: var(--large-field-width);
}

When you want to access this variable in JS you then simply do the following:

let fieldWidth = getComputedStyle(document.documentElement).getPropertyValue('--large-field-width');
// returns 65% rather than the px value. This is because the % has no relative
// size to the root or rather it's parent.

The other option would be to assign the default styling at the start of your script with:

element.style.width = '65%'

It can then be accessed with:

let width = element.style.width;

I personally prefer the first option but it really does depend on your use case. These are both technically inline styling but I like how you can update variable values directly with JS.

Solution 11 - Jquery

You could put styles you need to access with jQuery in either:

  1. the head of the document directly
  2. in an include, which server side script then puts in the head

Then it should be possible (though not necessarily easy) to write a js function to parse everything within the style tags in the document head and return the value you need.

Solution 12 - Jquery

There's nothing in jQuery, and nothing straightforward even in javascript. Taking timofey's answer and running with it, I created this function that works to get any properties you want:

// gets the style property as rendered via any means (style sheets, inline, etc) but does *not* compute values
// domNode - the node to get properties for 
// properties - Can be a single property to fetch or an array of properties to fetch
function getFinalStyle(domNode, properties) {
    if(!(properties instanceof Array)) properties = [properties]

    var parent = domNode.parentNode
    if(parent) {
        var originalDisplay = parent.style.display
        parent.style.display = 'none'
    }
    var computedStyles = getComputedStyle(domNode)

    var result = {}
    properties.forEach(function(prop) {
        result[prop] = computedStyles[prop]
    })

    if(parent) {
        parent.style.display = originalDisplay
    }

    return result
}

Solution 13 - Jquery

You can use the css(width) function to return the current width of the element.

ie.

var myWidth = $("#myElement").css("width");

See also: http://api.jquery.com/width/ http://api.jquery.com/css/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmontrealistView Question on Stackoverflow
Solution 1 - JqueryredexpView Answer on Stackoverflow
Solution 2 - JqueryTimofey DrozhzhinView Answer on Stackoverflow
Solution 3 - JqueryAdam LassekView Answer on Stackoverflow
Solution 4 - JqueryGumboView Answer on Stackoverflow
Solution 5 - JqueryddanoneView Answer on Stackoverflow
Solution 6 - JqueryLeonard PauliView Answer on Stackoverflow
Solution 7 - JqueryGregory MagarshakView Answer on Stackoverflow
Solution 8 - JqueryHorst WalterView Answer on Stackoverflow
Solution 9 - JqueryClean Code StudioView Answer on Stackoverflow
Solution 10 - JqueryDavid A. NugentView Answer on Stackoverflow
Solution 11 - JquerywheresrhysView Answer on Stackoverflow
Solution 12 - JqueryB TView Answer on Stackoverflow
Solution 13 - Jqueryuser267867View Answer on Stackoverflow