Accessing the browser’s stylesheets with CSSelection

October 20th, 2010 § 3 comments § permalink

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:

$('.annoyingDecoration').CSSeleciton('remove');

Get attributes for existing rule:

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