WEBDOOD.COM

Javascript addClassName, hasClassName and removeClassName

by webdood on Apr.07, 2010, under Javascript, Software Development

Useful CSS Class handling functions.

Here I present addClassName, hasClass and removeClassName and also my old implementation of Array.indexOf. Since this is built into JS these days, you probably won’t need it.

addClassName and removeClassName are useful functions because you can pass in space separated classNames and it will add/remove them all.

////////////////////////////////////////////////////////////////////////////////
//
// addClassName([object|string] oHTMLElement, string classNameToAdd)
// ===========
//  Adds classNameToAdd to an HTMLElement
//  Guaranteed not to add the same className twice.
//  - classNameToAdd can be a space separated list of classNames.
//  - You can pass in the id to an object or the actual object
//
////////////////////////////////////////////////////////////////////////////////
function addClassName(oHTMLElement, classNameToAdd) {
  if (typeof(oHTMLElement)=="string")  {
    oHTMLElement = document.getElementById(oHTMLElement);
  }
  if (oHTMLElement) {
    var theClassName = oHTMLElement.className;
    // If oHTMLElement already has a class name, some more work is needed
    if (theClassName && (theClassName.length > 0)) {
      var classNamesToAdd = classNameToAdd.split(" ");
      // If we only have one className to potentially add, take the "less work" approach
      if (classNamesToAdd.length===1 && ((" " + theClassName + " ").lastIndexOf(" " + classNameToAdd + " ") === -1) ) {
        oHTMLElement.className = oHTMLElement.className + " " + classNameToAdd;
      } else {
        var theClassNames = theClassName.split(" "),
              iEnd = classNamesToAdd.length,
              aClassName,
              theClassNamesToAddArray = [];
        for (var i=0;i<iEnd;i++) {
           aClassName = classNamesToAdd[i];
           if (theClassNames.indexOf(aClassName)===-1) {
             theClassNamesToAddArray.push( aClassName );
           }
        }
        oHTMLElement.className = oHTMLElement.className + " " +((theClassNamesToAddArray.length > 1) ? theClassNamesToAddArray.join(" ") : theClassNamesToAddArray[0]);
      }
    } else {
      // If oHTMLElement did not already have a class name, just add it
      oHTMLElement.className = classNameToAdd;
    }
  }
}

////////////////////////////////////////////////////////////////////////////////
//
// hasClassName([object|string] oHTMLElement, string classNameOfInterest)
//           Returns a boolean value of if an HTMLElement has the className of interest
//           You can pass in the id to an object or the actual object
//
////////////////////////////////////////////////////////////////////////////////
function hasClassName(oHTMLElement, classNameOfInterest) {
  return ((" " + oHTMLElement.className + " ").lastIndexOf(" " + classNameOfInterest + " ") > -1);
}
////////////////////////////////////////////////////////////////////////////////
//
// removeClassName([object|string] oHTMLElement, string classNameToRemove)
//           Removes classNameToRemove from an HTMLElement, if it exists.
//        - classNameToRemove can be a space separated list of classNames.
//        - You can pass in the id to oHTMLElement or the actual object
//
////////////////////////////////////////////////////////////////////////////////
function removeClassName(oHTMLElement, classNameToRemove) {
  if (typeof(oHTMLElement)=="string")  {
    oHTMLElement = document.getElementById(oHTMLElement);
  }
  if (oHTMLElement) {
    var theClassName = oHTMLElement.className;
    if (theClassName && (theClassName.length > 0)) {
      var theClassNameArray = theClassName.split(" "),
           classNamesToRemove = classNameToRemove.split(" "),
           iEnd = theClassNameArray.length,
           aClassName,
           theNewClassNameArray = [];
      for (var i=0;i<iEnd;i++) {
        aClassName = theClassNameArray[i];
        if (classNamesToRemove.indexOf(aClassName)===-1) {
          theNewClassNameArray.push( aClassName );
        }
      }
      switch (true) {
        case (theNewClassNameArray.length>1) :
          oHTMLElement.className = theNewClassNameArray.join(" ");
          break;
        case (theNewClassNameArray.length==1) :
          oHTMLElement.className = theNewClassNameArray[0];
          break;
        case (theNewClassNameArray.length==0) :
          oHTMLElement.className = "";
          break;
      }
    }
  }
}
////////////////////////////////////////////////////////////////////////////////
//
// Array.indexOf() - returns integer index where valueToSearchFor is in an Array
//
////////////////////////////////////////////////////////////////////////////////
if (Array.prototype.indexOf===undefined) {
  Array.prototype.indexOf = function( valueToSearchFor ) {
    var iEnd = this.length;
    var retVal = -1;
    for (var i=0;i<iEnd; i++) {
      if (this[i] == valueToSearchFor) {
        retVal = i;
        break;
      }
    }
    return retVal;
  };
}

by Shannon Norrell

:, , , , , , ,

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...

  • A List Apart
  • Dive into HTML5
  • Javascript: The Good Parts
  • QuirksMode.org