Is it possible to use jQuery to get the width of an element in percent or pixels, based on what the developer specified with CSS?

Viewed 78513

I'm writing a jQuery plugin and something I need to be able to do is determine the width of an element that the user specifies. The problem is that .width() or .css('width') will always report exact pixels, even if the developer has assigned it e.g. width:90% with CSS.

Is there any way to have jQuery output the width of an element in px or % depending on what the developer has given it with CSS?

10 Answers

It's 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.

For my purposes I extrapolated off MДΓΓ БДLL's answer.

Keep in mind, I'm only working with whole percentages.

    var getPercent = function(elem){
        var elemName = elem.attr("id");
        var width = elem.width();
        var parentWidth = elem.offsetParent().width();
        var percent = Math.round(100*width/parentWidth);
        console.log(elemName+"'s width = "+percent+"%");
    }

    getPercent($('#folders'));
    getPercent($('#media'));
    getPercent($('#player'));

Why has nobody answered this 'normally'? There are just those weirdly strange approches here.

USE VANILLA JAVASCRIPT

Don't do:

const a = $(element).width();
const b = $(element).css("width");

Do:

const c = $(element)[0].style.width;
Related