jQuery CSS plugin that returns computed style of element to pseudo clone that element?

Solution 1:

Two years late, but I have the solution you're looking for. Here's a plugin I wrote (by wrapping another guy's function in plugin format) which does exactly what you want, but gets all possible styles in all browsers, even IE.

jquery.getStyleObject.js:

/*
 * getStyleObject Plugin for jQuery JavaScript Library
 * From: http://upshots.org/?p=112
 *
 * Copyright: Unknown, see source link
 * Plugin version by Dakota Schneider (http://hackthetruth.org)
 */

(function($){
    $.fn.getStyleObject = function(){
        var dom = this.get(0);
        var style;
        var returns = {};
        if(window.getComputedStyle){
            var camelize = function(a,b){
                return b.toUpperCase();
            }
            style = window.getComputedStyle(dom, null);
            for(var i=0;i<style.length;i++){
                var prop = style[i];
                var camel = prop.replace(/\-([a-z])/g, camelize);
                var val = style.getPropertyValue(prop);
                returns[camel] = val;
            }
            return returns;
        }
        if(dom.currentStyle){
            style = dom.currentStyle;
            for(var prop in style){
                returns[prop] = style[prop];
            }
            return returns;
        }
        return this.css();
    }
})(jQuery);

Basic usage is pretty simple:

var style = $("#original").getStyleObject(); // copy all computed CSS properties
$("#original").clone() // clone the object
    .parent() // select it's parent
    .appendTo() // append the cloned object to the parent, after the original
                // (though this could really be anywhere and ought to be somewhere
                // else to show that the styles aren't just inherited again
    .css(style); // apply cloned styles

Hope that helps.

Solution 2:

It's not jQuery but, in Firefox, Opera and Safari you can use window.getComputedStyle(element) to get the computed styles for an element and in IE<=8 you can use element.currentStyle. The returned objects are different in each case, and I'm not sure how well either work with elements and styles created using Javascript, but perhaps they'll be useful.

In Safari you can do the following which is kind of neat:

document.getElementById('b').style.cssText = window.getComputedStyle(document.getElementById('a')).cssText;

Solution 3:

I dont know if you're happy with the answers you got so far but I wasn't and mine may not please you either, but it may help someone else.

After pondering upon how to "clone" or "copy" elements' styles from one to another I have come to realize that it was not very optimal of an approach to loop through n and apply to n2, yet we're sorta stuck with this.

When you find yourself facing these issues, you rarely ever need to copy ALL the styles from one element to another... you usually have a specific reason to want "some" styles to apply.

Here's what I reverted to:

$.fn.copyCSS = function( style, toNode ){
  var self = $(this);
  if( !$.isArray( style ) ) style=style.split(' ');
  $.each( style, function( i, name ){ toNode.css( name, self.css(name) ) } );
  return self;
}

You can pass it a space-separated list of css attributes as the first argument and the node you want to clone them to as the second argument, like so:

$('div#copyFrom').copyCSS('width height color',$('div#copyTo'));

Whatever else seems to "misalign" after that, I'll try to fix with stylesheets as to not clutter my Js with too many misfired ideas.

Solution 4:

Now that I've had some time to look into the problem and understand better how jQuery's internal css method works, what I've posted seems to work well enough for the use case that I mentioned.

It's been proposed that you can solve this problem with CSS, but I think this is a more generalized solution that will work in any case without having to add an remove classes or update your css.

I hope others find it useful. If you find a bug, please let me know.

Solution 5:

I like your answer Quickredfox. I needed to copy some CSS but not immediately so I modified it to make the "toNode" optional.

$.fn.copyCSS = function( style, toNode ){
  var self = $(this),
   styleObj = {},
   has_toNode = typeof toNode != 'undefined' ? true: false;
 if( !$.isArray( style ) ) {
  style=style.split(' ');
 }
  $.each( style, function( i, name ){ 
  if(has_toNode) {
   toNode.css( name, self.css(name) );
  } else {
   styleObj[name] = self.css(name);
  }  
 });
  return ( has_toNode ? self : styleObj );
}

If you call it like this:

$('div#copyFrom').copyCSS('width height color');

Then it will return an object with your CSS declarations for you to use later:

{
 'width': '140px',
 'height': '860px',
 'color': 'rgb(238, 238, 238)'
}

Thanks for the starting point.