Copying an HTMLElement’s styles to another … all of them

Kind of a thought experiment. You have one HTMLElement with a bunch of unknown style properties set on an ID selector or Element selector, and you need to get them over to another, completely different Element.

Paul and I came up with this:


// transfer an element's styles to another element.
// adam mcintyre & paul irish
// public domain, bitchezzz.

// we'll start with an h1.
var el = document.getElementsByTagName('h1')[0];

var cStyle = ''; 

for(var i in el.style){      

  if(typeof el.style[i] != 'function'){ 

    cStyle += i.replace(/([A-Z])/g,'-$1').toLowerCase() +
    ':' +
    (document.defaultView.getComputedStyle(el,null)
      .getPropertyValue(i) || 'none') +
    ';'
  }
}

// at this point cStyle is a big long string of
// display:block;opacity:1;css-text:none;parent-rule:none;azimuth:none;....

// h3's will grow up big and strong like h1's!!!!
document.getElementsByTagName('h3')[0].style.cssText = cStyle;

Leave a Reply

I'm Reading…
Search This Site

AddThis Feed Button

Need great hosting?

Categories