Wednesday, December 1, 2010

Add and Remove CSS classes programmatically in JavaScript

Here are a couple of functions to add and remove CSS classes programmatically in JavaScript.
Note: Get $() function code here if needed.


var DeveloperCaster = {
            AddCssClass: function (id, className) {
                if ($(id).className.length <= 0) {
                    $(id).className = className;
                } else {
                  if ($(id).className.search(className) == -1) {
                     $(id).className = $(id).className + ' ' + className;
                  }
                }
            },
            RemoveCssClass: function (id, className) {
              if ($(id).className.length > 0) {
                 if ($(id).className.search(className) != -1) {
                   $(id).className = $(id).className.replace(className, "");
                  }
              }
            }
        }

Example of how to use it:


CSS
    <style type="text/css">

        .mystyle
        {
            border:1px solid #333333;
            width:100px;
            height:50px;
        }
    </style>

JavaScript


window.onload = function () {
    DeveloperCaster.RemoveCssClass('a', 'mystyle');
};


HTML
<div id="a" class="mystyle"></div>






2 comments:

  1. Thanks a lot. I adapted this with great success. But I thought I'd comment: Beware the search and replace functions. As-is, this will falter if you use classes with similar names.

    e.g. you have a class called "active", and one called "inactive" the search function will find both when searching for "active", and worse, the replace function will wipe out "active" from "inactive", leaving you with "in".

    I dodged this bullet by changing my class names to e.g. "active" and "inActive", but for a project with a bigger style sheet, this could get ugly. I'm sure there are ways to be more specific with these functions, so keep that in mind.

    ReplyDelete
  2. @mmseng

    Thanks for pointing that out; I didn't think about it.

    ReplyDelete