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.


Changing Element Styles example

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

Some More Text

CSS Code

<style>
	#styleText {
		font-size: 20px;
	}
</style>
				

JavaScript Code

var size = 20;
function makeLarger() {
	var element = document.getElementById('someMoreText');
	size+=5;
	element.style.fontSize = size+"px";
}
function makeSmaller() {
	var element = document.getElementById('someMoreText');
	size-=5;
	element.setAttribute('style', 'font-size: '+size+'px');
}
function makeRed() {
	var element = document.getElementById('someMoreText');
	element.style.color = "red";
}