Changing Classes in JavaScript

A Message From A Beautiful Site, LLC.
We spent over a year redeveloping Surreal CMS to make it the best hosted content management system out there. If you have a website, it’s worth checking out. Learn More »

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>