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.


Element Class Names example

This example demonstrates how to change an specific element's class.

Some Even More Text

CSS Code

<style>
	.classGreen {
		color: green;
	}
	.classRed {
		color: red;
	}
</style>
			

JavaScript Code

function changeToGreenClass() {
	var element = document.getElementById('class_ex');
	element.className = "classGreen";
}
function changeToRedClass() {
	var element = document.getElementById('class_ex');
	element.className = "classRed";
}
function removeClass() {
	var element = document.getElementById('class_ex');
	element.className = "";
}