I\'m looking for a way using jQuery to return an object of computed styles for the 1st matched element. I could then pass this object to another call of jQuery\'s css method
.css()
$('body').css(); // -> { ... } - returns all styles
$('body').css('*'); // -> { ... } - the same (more verbose)
$('body').css('color width height') // -> { color: .., width: .., height: .. } - returns requested styles
$('div').css('width height', '100%') // set width and color to 100%, returns self
$('body').css('color') // -> '#000' - native behaviour
(function($) {
// Monkey-patching original .css() method
var nativeCss = $.fn.css;
var camelCase = $.camelCase || function(str) {
return str.replace(/\-([a-z])/g, function($0, $1) { return $1.toUpperCase(); });
};
$.fn.css = function(name, value) {
if (name == null || name === '*') {
var elem = this.get(0), css, returns = {};
if (window.getComputedStyle) {
css = window.getComputedStyle(elem, null);
for (var i = 0, l = css.length; i < l; i++) {
returns[camelCase(css[i])] = css.getPropertyValue(css[i]);
}
return returns;
} else if (elem.currentStyle) {
css = elem.currentStyle;
for (var prop in css) {
returns[prop] = css[prop];
}
}
return returns;
} else if (~name.indexOf(' ')) {
var names = name.split(/ +/);
var css = {};
for (var i = 0, l = names.length; i < l; i++) {
css[names[i]] = nativeCss.call(this, names[i], value);
}
return arguments.length > 1 ? this : css;
} else {
return nativeCss.apply(this, arguments);
}
}
})(jQuery);
Main idea is taken from Dakota's & HexInteractive's answers.