Changing Classes in JavaScript

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;
    }
}

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

Hi ! thanks for this very cool function. I just notice that the link "example" lead to a 404 page because you wrote : "changeClass.htm" instead of "changeclass.htm"

Hope it helps ;)

Regards

bruno bichet on Nov 16th, 2008

Add a comment

Name*

Email*

Never, ever sold or spammed :)

Homepage

Comment*

Sorry, plain text only :(