Posted By

Pjotor on 02/26/11


Tagged

jquery


Versions (?)

CSS class/id/object style extractor


 / Published in: JavaScript
 

URL: http://pjotor.com

I needed something that could extract style from a css-class, even if no DOM-object had the class; thus this little plugin.

Usage: $.cssStyle(".className") Returns a Object with key/value pairs corresponding to the style of the CSS-class "className"

  1. // Style sheet getter
  2. // Returns style as object usage:
  3. // var classNameColor = $.cssStyle(".className").color;
  4.  
  5. ;(function ($) {
  6.  
  7. $.cssStyle = function (selector) {
  8. var sels = selector.match(/(^|\#|\.|\s)[\w|-]+/g),
  9. ret = {},
  10. style, sel, i;
  11. $.each(
  12. document.styleSheets, function () {
  13. var rules = this.cssRules || this.rules;
  14. $.each(rules, function (n, v) {
  15. for (i in sels) {
  16. sel = new RegExp("(?:^|\\s)(" + sels[i].replace(/^\s+/, "") + ")(?=,|$)");
  17. if (v.selectorText && sel.test(v.selectorText)) {
  18. $.extend(ret, $.map.str(v.style.cssText));
  19. }
  20. }
  21. });
  22. });
  23. return ret;
  24. }
  25. })(jQuery);
  26.  
  27. // a little string mapper (string to object)
  28. ;(function ($) {
  29. $.map.str = function (s, objDev, keyDev) {
  30. objDev = objDev || ";", keyDev = keyDev || ":";
  31. if (s.indexOf(keyDev) === -1) return s;
  32. var d = s.split(objDev);
  33. var r = {};
  34. var key, val;
  35. for(par in d) {
  36. val = d[par].split(keyDev);
  37. key = $.trim(val.splice(0, 1).join());
  38. val = $.trim(val.join(keyDev));
  39. if (val.length > 1) {
  40. r[$.camelCase(key)] = val;
  41. }
  42. }
  43. return r;
  44. }
  45. })(jQuery);
  46.  
  47. // CamelCase object keys (ripped from jQuery since it seems to come and go in core)
  48. ;(function ($) {
  49. if ( !$.isFunction($.camelCase) ) {
  50. $.camelCase = function (string) {
  51. return string.replace(/-([a-z])/ig, function (all, letter) {
  52. return letter.toUpperCase();
  53. });
  54. }
  55. }
  56. })(jQuery);

Report this snippet  

You need to login to post a comment.