Extend Object with method that handles CSS values in javascript

If you are working with and need to for instance add or subtract a value to a value like “15px” or “3em” this method “()” will come in handy.

Simply add the code somewhere in the top to extend the “Object” object.


The method is used as follows:


which will return an object:

{ 'value':10, 'unit':'px' }

Simple but very usefull!


Object.prototype.getCSSValueAndUnit = function() {
  var oReUnit = new RegExp('[0123456789\.-]', 'ig');
  var sOriginal = this.toString();
  var sUnitRaw = sOriginal.replace(oReUnit, '')
  var sUnit = sUnitRaw.replace(new RegExp(' ', 'ig'), '');
  var vValue = parseFloat(sOriginal.replace(sUnitRaw,''));
  return {'value':vValue, 'unit':sUnit};

Leave a Reply