Changing Classes in JavaScript
Written by Cory S.N. LaViska on July 14th, 2007
A simple JavaScript function that changes all elements of a specified class to another specified class.
Here is a handy JavaScript function that changes any element of class oldClass to newClass in the current document. This is especially useful for changing styles on the fly using CSS classes instead of hard-coded style values.
function changeClass(oldClass, newClass) {
var elements = document.getElementsByTagName("*");
for( i = 0; i < elements.length; i++ ) {
if( elements[i].className == oldClass ) elements[i].className = newClass;
}
}
var elements = document.getElementsByTagName("*");
for( i = 0; i < elements.length; i++ ) {
if( elements[i].className == oldClass ) elements[i].className = newClass;
}
}
I've set up an example of how changeClass() can be used to show/hide sub-lists, but this is just one of them many possible applications for this function.













Comments
— bruno bichet on Nov 16th, 2008