Three functions, one to return a CSS style object, one to create a new CSS rule, and one to delete a CSS style object. Dynamically create, change, and delete stylesheets. Easy to use and heavily commented.
- Created by: Patrick Hunlock
- Web Site: http://www.hunlock.com
- Posted: February 21, 2007
getCSSRule — Return a CSS rule
This function will accept a CSS selector (classname, divname, etc) and if it exists will pass back the style object. Lets say you have a class called
.global. To retrieve this style all you have to do is the following:
var global = getCSSRule('.global');
Global is now a pointer to the stylesheet rule for the class
global and you can now manipulate it pretty much exactly like you would manipulate any getElementById object. For instance, to give the class an overline and underline property just issue the following command
This works for any defined selector. If, for instance, you have an ID match
#global then you would retrieve it using:
var global = getCSSRule('#global');
And of course it works on raw HTML elements. For instance to get your style for all the paragraph tags:
var global = getCSSRule('P');
getCSSRule goes by exact match. So if you have a rule for
.global DIV you will need to specify
.global DIV to get that rule, just
.global won't cut it. If getCSSRule can't find the selector you're looking for it will return FALSE.
killCSSRule — Delete a CSS rule
This is a very simple function. All it does is call getCSSRule with your ruleName and a delete flag. When getCSSRule finds your rule it will delete it and any objects on the page with that style will instantly become unstyled. Again this is an exact match function.
addCSSRule — Create a new CSS rule
This is a really cool function. It basically accepts a rule name, creates an empty ruleset in the first stylesheet, and then returns the stylesheet object it created. Why is it cool? Well if you pass it a string
.globalTwo would create a new classname called
globalTwo and passing it
#someDiv would let you style some division with an ID of
someDiv. Here's an example:
var global2 = addCSSRule('.global2'); global2.style.backgroundColor='green'; var someDiv = addCSSRule('#someDiv'); someDiv.style.fontWeight='bold';
The caveat is that this works with the first stylesheet on the page regardless of the media type. So make sure your screen CSS appears as the first stylesheet if you want to use addCSSRule, otherwise — while it may appear your new styles are going into a black-hole, your printouts may end up looking very funky indeed!
Paste this source code into the designated areas.
Paste this code into the
HEAD section of your HTML document.