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.


Accessing style sheets example

This example demonstrates how to access, create, and remove style sheets. Press the button to add and remove stylesheets!

Number of style sheets on page:

CSS Code

<style id='e1_style'>
	#e1 {
		font-weight: bold;
		font-size: 115%;
		color: green;
	}
</style>
Or (only one added at a time)
<style id='e1_style'>
	#e1 {
		border: 2px solid black;
		background-color: blue;
	}
</style>
			

JavaScript Code

var e1_toggle = true;
function toggleStyleSheet() {
	var node = document.getElementById('e1_style');
	node.parentNode.removeChild(node);
	var sheet = document.createElement('style')
	sheet.id = 'e1_style';
	if(e1_toggle) {
		sheet.innerHTML = "#e1 {border: 2px solid black; background-color: blue;}";
	} else {
		sheet.innerHTML = "#e1 {font-weight: bold; font-size: 115%; color: green;}";
	}
	document.body.appendChild(sheet);
	e1_toggle = ! e1_toggle;
	updateNumberOfStyleSheets();
}
function updateNumberOfStyleSheets(){
	document.getElementById('numOfStyleSheets').innerHTML
		= document.styleSheets.length;
}