Skip to content
Advertisement

Get the computed style and omit defaults

I’m trying to get the current runtime style of an element and filter out properties that have default values. For example, with markup like this:

<style>
    .foo { background: red }
    span { font-size:30px }
</style>


<div style="color: blue">
    <span id="bar" class="foo">hello</span>
</div>

I’d like the result to be:

 background-color: red;
 color: blue;
 font-size: 30px;

I tried window.getComputedStyle, but it returns a lot of stuff and I’m unsure how to filter out defaults. Any pointers will be appreciated.

Advertisement

Answer

there you go, i did this by adding a new dummy DOM element, to know which styles are default for any element.

/**
 * IE does not have `getComputedStyle` 
 */

window.getComputedStyle = window.getComputedStyle || function( element ) {
  return element.currentStyle;
}

/**
 * get computed style for an element, excluding any default styles
 *
 * @param {DOM} element
 * @return {object} difference
 */

function getStylesWithoutDefaults( element ) {

  // creating an empty dummy object to compare with
  var dummy = document.createElement( 'element-' + ( new Date().getTime() ) );
  document.body.appendChild( dummy );

  // getting computed styles for both elements
  var defaultStyles = getComputedStyle( dummy );
  var elementStyles = getComputedStyle( element );

  // calculating the difference
  var diff = {};
  for( var key in elementStyles ) {
    if(elementStyles.hasOwnProperty(key)
          && defaultStyles[ key ] !== elementStyles[ key ] )
    {
      diff[ key ] = elementStyles[ key ];
    }
  }

  // clear dom
  dummy.remove();

  return diff;
}


/**
 * usage
 */

console.log( getStylesWithoutDefaults( document.getElementById( 'bar' ) ) );

Notes:

  • the result will have some extra properties, not only those you’ve mentioned.

demo – console should be opened

Advertisement