Grow your CSS skills. Land your dream job.

Last updated on:

addClass Function

If you are going library-free, you might need to roll your own function like this.

function addClass(id,new_class){
       var i,n=0;

       new_class=new_class.split(",");

       for(i=0;i<new_class.length;i++){
               if((" "+document.getElementById(id).className+" ").indexOf(" "+new_class[i]+" ")==-1){
                       document.getElementById(id).className+=" "+new_class[i];
                       n++;
               }
       }

       return n;
}

Usage

<div id="changeme" class="big red"></div>
<button onclick="addClass('changeme', 'round')">Add a class</button>

Reference URL

Comments

  1. Modern browsers have a ‘classList’ dom element attribute:

    element.classList.add('classname');

    There also exists a fix for IE 8+, more info here: developer.mozilla.org/en/DOM/element.classList

    Also it is bad practice to use JavaScript inline with html elements, the convention is to attach it via as event handler.

    This could be a possible alternative:

    var addClass = function(_element, _classes) {
      var classList, item, _i, _len;
      classList = _element.classList;
      for (_i = 0, _len = classes.length; _i < _len; _i++) {
        item = classes[_i];
        classList.add(item);
      }
      return _element;
    };
    • I’m sorry there is a small typo in my code:

      var addClass = function(_element, _classes) {
        var classList, item, _i, _len;
        classList = _element.classList;
        for (_i = 0, _len = _classes.length; _i < _len; _i++) {
          item = _classes[_i];
          classList.add(item);
        }
        return _element;
      };

      Also, this would be executed as such:

      addClass(element, ['class1', 'class2']);
    • D

      @Liam: Great code! Adjusted it slightly by adding a toggle function. This way I can add/remove classes. In my case to show/hide the sibling elements in a table.

      var addClass = function(_element, _classes) {
          var classList, item, _i, _len;
          classList = _element.classList;
          for (_i = 0, _len = _classes.length; _i < _len; _i++) {
              item = _classes[_i];
              if (classList.length <= _len) {
                  classList.add(item);
              } else {
                  classList.remove(item);
              }
          }
          return _element;
          };
      
  2. This snippet assumes that a U+0020 space is used to separate class names. While that would probably work in most situations, it’s important to note that there’s more than just one space character in HTML.

  3. nonae
    Permalink to comment#

    @the guys that didn’t like it:

    simply don’t use it. Nobody is forcing you to use it.

    I think it is a great snippet. The “”+word+”” search is pure awesomeness, this totally prevents any kind of unexpected results.

    I love this website, I really didn’t think they will put my snippet

    • nonae
      Permalink to comment#

      They didn’t explain what the “return n;” was for.

      it is just to know how many classes where successfully added. That option was handy for me (and if someone is not really going to use it, well simply delete that line)

  4. Guys what if i want to remove these classes automatically when i add a Class on some other element ?

Leave a Comment

Current day month ye@r *

*May or may not contain any actual "CSS" or "Tricks".