Skip to content

Instantly share code, notes, and snippets.

@podgorniy
Created January 3, 2012 18:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save podgorniy/1556224 to your computer and use it in GitHub Desktop.
Save podgorniy/1556224 to your computer and use it in GitHub Desktop.
Get object with computed styles from the node
/**
* Return object with computed styles
* @param {DOMNode} node
* @param {String|Array} styles_to_get "float colot padding-top" or ["float", "padding-top", "padding-bottom"]
* @return {Object} list of styles values {
* "float" : "none",
* "color" : "#000000"
* }
*/
function get_computed_styles(node, styles_to_get) {
'use strict';
var res = {},
current_styles,
camel_case_style_name,
second_param_type,
i;
// Get object, representing current styles
if (node.currentStyle) {
current_styles = node.currentStyle;
} else if (window.getComputedStyle) {
current_styles = window.getComputedStyle(node);
} else {
throw (new Error('get_computed_styles: could not get styles'));
}
second_param_type = Object.prototype.toString.call(styles_to_get);
// Create array of styles to get, if possible
if (styles_to_get) {
if (second_param_type === '[object String]') {
styles_to_get = styles_to_get.split(/\s+/);
} else if (second_param_type !== '[object Array]') {
throw (new Error('get_computed_styles: second param string or array expected, but got ' + second_param_type));
}
// Collect styles value into result object
for (i = 0; i < styles_to_get.length; i += 1) {
camel_case_style_name = styles_to_get[i].replace(/-(.)/, function (match, first_letter) {
return first_letter.toUpperCase();
});
if (camel_case_style_name === 'float') {
res[styles_to_get[i]] = current_styles.cssFloat || current_styles.styleFloat;
} else {
res[styles_to_get[i]] = current_styles[camel_case_style_name];
}
}
} else {
res = current_styles;
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment