Changing Classes in JavaScript

A note from A Beautiful Site’s founder: We developed Surreal to be easy for you and your clients. If you’re a web designer, you should take a look at the simple, hosted CMS that’s changing the way content is managed. Surreal integrates in moments and is trusted by over 18,000 websites. Try it out for free and let us know what you think! Visit Website »

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;
    }
}
If you enjoyed this article, please share it with a friend!

One Response to Changing Classes in JavaScript

  1. bruno bichet says:

    Hi! thanks for this very cool function.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>