JavaScript Add/Remove a Class to The Element

Here are some methods to adding or removing a class to an elements.

Bear in mind that when an element already has a class name defined, its influence on the element is tied to its position in the string of class names. Later classes override earlier ones if there is a conflict. Adding a class to an element ought to move the class name to the sharp end of the list, if it exists already.

Adding Class

  • Cross Compatible

    To add a class to an element without removing/affecting existing values, append a space and the new classname:

    To replace all existing classes with one or more new classes, set the className attribute:

    In the following example we add a classname to the body element. This is IE-8 compatible.

    This is shorthand for the below:

  • Performance

    If your more concerned with performance over cross-compatibility you can shorten it to the following which is 4% faster (classList is not supported in IE <= 9 or Safari <=5.0).

  • Convenience

    Alternatively you could use jQuery but the resulting performance is significantly slower with 94% slower according to jsPerf

Removing the class

  • Pure javascript without jQuery

  • Performance

    Using jQuery selectively is the best method for removing a class if your concerned with performance

Functions of Adding & Removing Class

Using Prototype

Using YUI


Leave a Reply

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