How to get just numeric part of CSS property with jQuery?

Viewed 133596

I need to do a numeric calculation based on CSS properties. However, when I use this to get info:

$(this).css('marginBottom')

it returns the value '10px'. Is there a trick to just getting the number part of the value no matter whether it is px or % or em or whatever?

15 Answers
parseInt($(this).css('marginBottom'), 10);

parseInt will automatically ignore the units.

For example:

var marginBottom = "10px";
marginBottom = parseInt(marginBottom, 10);
alert(marginBottom); // alerts: 10

This will clean up all non-digits, non-dots, and not-minus-sign from the string:

$(this).css('marginBottom').replace(/[^-\d\.]/g, '');

UPDATED for negative values

With the replace method, your css value is a string, and not a number.

This method is more clean, simple, and returns a number :

parseFloat($(this).css('marginBottom'));
parseFloat($(this).css('marginBottom'))

Even if marginBottom defined in em, the value inside of parseFloat above will be in px, as it's a calculated CSS property.

$(this).css('marginBottom').replace('px','')

I use a simple jQuery plugin to return the numeric value of any single CSS property.

It applies parseFloat to the value returned by jQuery's default css method.

Plugin Definition:

$.fn.cssNum = function(){
  return parseFloat($.fn.css.apply(this,arguments));
}

Usage:

var element = $('.selector-class');
var numericWidth = element.cssNum('width') * 10 + 'px';
element.css('width', numericWidth);

parseint will truncate any decimal values (e.g. 1.5em gives 1).

Try a replace function with regex e.g.

$this.css('marginBottom').replace(/([\d.]+)(px|pt|em|%)/,'$1');

Should remove units while preserving decimals.

var regExp = new RegExp("[a-z][A-Z]","g");
parseFloat($(this).css("property").replace(regExp, ""));
Related