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>

Comments

  1. User Avatar
    Liam Goodacre
    Permalink to comment#

    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;
    };
    • User Avatar
      Liam Goodacre
      Permalink to comment#

      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']);
    • User Avatar
      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. User Avatar
    Mathias Bynens
    Permalink to comment#

    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. User Avatar
    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

    • User Avatar
      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. User Avatar
    Thabang

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

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-searchicon-staricon-tag