Accessing the browser’s stylesheets with CSSelection

October 20th, 2010 § 3 comments

When writing applications that modify the DOM there’s one thing to keep in mind: your code will not be the only code touching the DOM. Defensive code is good code.

With defensive programming in mind there sometimes exists a need to peek into the CSS that is loaded into the browser. Say an application your writing depends on user-based styles that are dynamically loaded in. It’d be nice to inject those styles into the document CSS and know you’re not overwriting anything. Perhaps your code is meant to take an existing style and modify it.

To this end I present a work-in-progress of my first jQuery plugin, CSSelection.

Code: View CSSelection on GitHub

Download jquery.CSSelection.js

CSSelection start by accepting a jQuery selector. With that selector you can read the current styles applied to that selector, add new styles, create such a selector if one does not exist or even remove the current selector from the stylesheet. I tried to keep the interface predictable to jQuery users at the expense of a bit of extra code. Passing no arguments retrieves the current rules, if any, of the selector. Passing the string “remove” does as expected to first found matching selector in the style sheets. Finally passing an object literal with rules will either add them to the stylesheet or modify the matching selector.

While this code is used in production I’ll still call it beta as bugs are cropping up in IE9 and are sure to arrive in future revs of Safari and Firefox. Enjoy!

Usage examples

How to create a rule for HTML elements:

$('p').CSSelection({rules: {'font-size': '120%', 'color': 'red', 'background-color': '#fff'}});

Modifying existing CSS rule/add new rule:

$('.important').CSSelection({rules: {'text-decoration': 'underline overline', 'background': 'yellow'}});

Delete a CSS rule:


Get attributes for existing rule:

var attrs = $('.wickedAwesomeClass').CSSelection();

Tagged , ,

§ 3 Responses to Accessing the browser’s stylesheets with CSSelection"

  • rainabba says:

    I’ve been looking for just this sort of functionality but can’t figure out your syntax despite what i’m sure is a great write-up. Mind throwing some examples up? In particular, how to modify an existing rule based on a simple .class selector.

  • adam says:

    I’ve updated the post with some simple usage examples. Let me know if that helps.

  • tmont says:

    Cool stuff! Looks pretty solid, too.

    I think you might have a problem if your passed-in rules object has one of the “unsafe” CSS properties, like “float”. Your loop to turn them into JavaScript style properties needs to special case “float” and replace it with “cssFloat” (I can’t remember off the top of my head if there are any more like that). Although I’m not very familiar with the stylesheet API so maybe it’s not necessary…