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 :)

  • Pingback: Daniele Mazzini()

  • Pingback: hanachin()

  • http://twitter.com/xyzzyb Stephen Ball

    Instead of changing the style rules directly, why not make a jQuery selector for what you want to change and use the .css() jQuery function?

    http://api.jquery.com/css/

    e.g.

    $(‘p.some-interesting-class’).css(‘color’, ‘#eee’);

    • Anonymous

      My use case was that I needed to change the width of elements which are deleted and recreated quite often. By using the .css() jQuery function, you can change the width of the existing elements, but when you create a new one, it gets its width from the style rule.

      By changing the rule itself, every new element gets the updated width… et voilà, everything works :)

  • Pingback: わかめにゅーす(HTML/CSS)()

  • Pingback: Israel R Varela()