While looking for compact Javascript addClass and removeClass functions, I stumbled upon http://snipplr.com/view/3561/addclass-removeclass-hasclass/.

This code allows for a few optimizations:

  • The ‘match’ method is deprecated, ‘test’ should be used instead.
  • The ‘addClass’ function references a non-existing ‘this’ object.
  • The ‘removeClass’ function declares a new variable ‘reg’, which is unnecessary.
  • The ‘removeClass’ function doesn’t handle multiple classes well.

Here is my improved version:

function hasClass(el, name) {
   return new RegExp('(\\s|^)'+name+'(\\s|$)').test(el.className);
function addClass(el, name)
   if (!hasClass(el, name)) { el.className += (el.className ? ' ' : '') +name; }
function removeClass(el, name)
   if (hasClass(el, name)) {
      el.className=el.className.replace(new RegExp('(\\s|^)'+name+'(\\s|$)'),' ').replace(/^\s+|\s+$/g, '');

Hope this helps someone somewhere.