Convert css width string to regular number Convert css width string to regular number jquery jquery

Convert css width string to regular number


If it always returns in px format, "100px", "50px" etc (i.e. not "em" or percent), you could just...

var width = parseInt($("#myelem").css("width"),10); // always use a radix

or

var width = parseInt(element.style.width,10); // always use a radix

It ignores the "px" suffix so you should be good to go.

Although deep down I'm thinking that something isn't right if $("#myelem").width() isn't working.

Note on hidden elements.

If you are adding jQuery to progressively enhance you page, the element you are calculating should be visible when the page first loads. So you should get the width before you initially hide the element. By doing this, $("#myelem").width() will work.

var myWidth = 0;$(document).ready( function () {    myWidth = $("#myelem").width();    $("#myelem").hide();});


In plain JavaScript:

parseInt('100px', 10)

Works with "100em", "100%", and even with: "100". No need for any Regular Expression patterns.


You could remove non-numericals with a regular expression and then just convert to a number. This works no matter how you define the width (px, em, %, pt). Preserves decimal points too.

vanilla javascript

Number(elem.style.width.replace(/[^\d\.\-]/g, ''));

jQuery

Number($elem.css('width').replace(/[^\d\.\-]/g, ''));