Update CSS rules with 5 lines of CoffeeScript

I recently (ie, today) had to find a way to update a CSS rule dynamically in javascript. jQuery, my library of choice, doesn’t offer this functionality – and I really wonder why – so I looked around a little and found how to do it with plain javascript.

As I’m actually using CoffeeScript, I decided to rewrite it in that language and make it a generic function; it could be useful to others, so, there you go:

@updateCSS = (selector, styles) ->
  for sheet in document.styleSheets
      for rule in sheet.cssRules || sheet.rules || []
        if rule.selectorText == selector
          for style, value of styles
            rule.style[style] = value

You can also find an usage example (and play with it yourself) on jsfiddle. Enjoy 🙂