jQuery copy all css from one element to another
September 18, 2012 20:46:12 Last update: September 18, 2012 20:46:12
There's no easy way in jQuery (like one or two lines) to copy all CSS properties (inline, inherited, native, etc.) from one element to another. Such as, create a
Upshots provides a simple jQuery plugin that seemed to work. I copy the code below.
<p> element that has the same CSS as an existing <div> element.
Upshots provides a simple jQuery plugin that seemed to work. I copy the code below.
$.fn.copyCSS = function(source){ var dom = $(source).get(0); var style; var dest = {}; if(window.getComputedStyle){ var camelize = function(a,b){ return b.toUpperCase(); }; style = window.getComputedStyle(dom, null); for(var i = 0, l = style.length; i < l; i++){ var prop = style[i]; var camel = prop.replace(/\-([a-z])/g, camelize); var val = style.getPropertyValue(prop); dest[camel] = val; }; return this.css(dest); }; if(style = dom.currentStyle){ for(var prop in style){ dest[prop] = style[prop]; }; return this.css(dest); }; if(style = dom.style){ for(var prop in style){ if(typeof style[prop] != 'function'){ dest[prop] = style[prop]; }; }; }; return this.css(dest); }; // usage... // $('#my-element').copyCSS('#another-element'); // or... // $('#my-element').copyCSS(someReferenceToAnElement);