I've got a simple input field as follows:
<input type="text" name="search_location" id="search_location" placeholder="Any Location" autocomplete="off">
Using jQuery, I'm trying to get all styles associated with it. The code for this looks like this (got it from this stackoverflow thread):
// Get all styles associated with element
var style = css(jQuery("#elementToGetAllCSS"));
function css(a) {
var sheets = document.styleSheets, o = {};
for (var i in sheets) {
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules) {
if (a.is(rules[r].selectorText)) {
o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
}
}
}
return o;
}
function css2json(css) {
var s = {};
if (!css) return s;
if (css instanceof CSSStyleDeclaration) {
for (var i in css) {
if ((css[i]).toLowerCase) {
s[(css[i]).toLowerCase()] = (css[css[i]]);
}
}
} else if (typeof css == "string") {
css = css.split("; ");
for (var i in css) {
var l = css[i].split(": ");
s[l[0].toLowerCase()] = (l[1]);
}
}
return s;
}
// Apply styles to target element
var style = css(jQuery("#elementToGetAllCSS"));
jQuery("#search_location").css(style);
Everything is peachy, except when it comes to CSS pseudo selectors like :before and :after at which point I get an "unrecognized expression" console error.
Any ideas?
EDIT - My Solution
The answer below will work, although I'm a bit concerned about how future proof the answer will be. With that in mind, there's an alternative that seems to be working fine:
$.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, l = style.length; i < l; i++){
var prop = style[i];
var camel = prop.replace(/\-([a-z])/g, camelize);
var val = style.getPropertyValue(prop);
returns[camel] = val;
};
return returns;
};
if(style = dom.currentStyle){
for(var prop in style){
returns[prop] = style[prop];
};
return returns;
};
return this.css();
}
var styles = $('elementToGetAllCSS').getStyleObject();
this.css('search_location);