Cloning CSSStyleDeclaration from getComputedStyle

Benchmark created by MrOrz on


Description

I need to store a copy of CSSStyleDeclaration.

There are two way to clone it:

  1. by enumerating non-digit attributes using for-in
  2. by splitting CSSText string
  3. by enumerating digit attributes

Setup

window.computed = window.getComputedStyle(document.body);
    window.clonedTarget = {};

Test runner

Ready to run.

Testing in
TestOps/sec
Enumerate all non-numeric attributes
var attr;

for(attr in computed){
  if(computed.hasOwnProperty(attr) && isNaN(+attr) &&
     attr !== 'cssText' && attr !== 'length' && attr !== 'parentRule'){
    clonedTarget[attr] = computed[attr];
  }
}
ready
Splitting cssText results
computed.cssText.split(';').slice(0, -1).forEach(function(declaration){
  var colonPos = declaration.indexOf(':');
  var attr = declaration.slice(0, colonPos).trim();
  if(attr.indexOf('-') === -1){ // Remove attributes like "background-image", leaving "backgroundImage"
    clonedTarget[attr] = declaration.slice(colonPos+2);
  }
});
ready
by enumerating digit attributes
var i, attr;

for(i=0; i<computed.length; i+=1){
  attr = computed[i];
  clonedTarget[attr] = computed[attr];
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.