Javascript addClass/removeClass functions

While looking for compact Javascript addClass and removeClass functions, I stumbled upon

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.

3 thoughts on “Javascript addClass/removeClass functions

  1. A couple of things though.
    1. don’t use className as a variable and a property, it’s confusing.
    2. there’s a surplus ; on the end of the hasClass function

    thanks for the script.

Leave a Reply

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