Dynamic style: Manipulating CSS with JavaScript Examples

Note: Some of the example code shown below is not the full code being executed. To make things as simple as possible I wanted to just show the critical code pertaining to style manipulation, thus the code that deals with browser differences is not shown. To see the full code one can view the source code.


Adding and Removing Rules example

This example demonstrates how to add and remove rules from a style element.

CSS rules of our style sheet. Numbered starting at zero in cssRules

some text in a P tag

CSS Code

<style title="e3_style">
	.not-applied-class1 {
		border: 2px solid black;
	}
	.not-applied-class2 {
		font-size: 15px;
	}
	.not-applied-class3 {
		background-color: blue;
	}
	.not-applied-class4 {
		margin: 10px;
	}
</style>
					

JavaScript Code

var e3_style_on = false;
function getStyleSheet() {
	for(var i=0; i<document.styleSheets.length; i++) {
		var sheet = document.styleSheets[i];
		if(sheet.title == 'e3_style') {
			return sheet;
		}
	}
}
var rule_sheet = getStyleSheet();
function changeText() {
	if(!e3_style_on) {
		rule_sheet.insertRule("p { color: red;}", 2);
	}
	e3_style_on = true;
	showRules();
}
function resetText() {
	if(e3_style_on) {
		rule_sheet.deleteRule(2);
	}
	e3_style_on = false;
	showRules();
}
			

Note: IE does not implement rules according to the standard.
Instead of the attribute cssRules it uses rules; IE also uses removeRule instead of deleteRule and addRule(selector, rule, index) instead of insertRule.