Detect if an element contains a class with pure JavaScript

17

In jQuery, we have the code

$("#elemento").hasClass("nomeDaClasse");

This indicates whether an element contains a particular CSS class. How can I achieve the same with pure JavaScript?

    
asked by anonymous 17.03.2014 / 21:09

3 answers

16

In modern browsers you can use the classList native property, so syntax will be:

div.classList.contains("foo");

Demonstration in JSFiddle

This "new" classList property (English) is supported from the following versions:

  • Chrome 8 +;
  • Firefox 3.6 +;
  • IE10 +;
  • Opera 11.5 +;
  • Safari 5.1+

To use "old" javascript you can also use for example:

/**
 * Tem Classe
 * Verifica se o elemento do DOM tem determinada classe de CSS
 *
 * @param object el        Elemento do DOM
 * @param string classe    O nome da classe de CSS
 *
 * @return boolean
 */
function temClasse(el, classe) {
    return !!(el.className.split(' ').indexOf(classe) + 1);
}

Demonstration in JSFiddle

    
17.03.2014 / 21:29
8

Your element has the className property that contains all the classes attached to it. From there, you can create a simple JavaScript function to detect if an element has a CSS class:

function hasClass(elemento, classe) {
    return (' ' + elemento.className + ' ').indexOf(' ' + classe + ' ') > -1;
}

Example usage: JsFiddle

Translated from the original issue into SOEN, after I resolve my question there

    
17.03.2014 / 21:09
5

I think this is the most compatible with most browsers and situations, as well as allowing to check more than one class:

Node.prototype.hasClass = function(value) {
    var
        has = true,
        names = String(value).trim().split(/\s+/);

    for(var i = 0, len = names.length; i < len; i++){
        if(!(this.className.search(new RegExp('(?:\s+|^)' + names[i] + '(?:\s+|$)', 'i')) > -1)) {
            has = false;
            break;
        }
    }
    return has;
};

Example usage:

element.hasClass('class-name');

Example with more than one class:

element.hasClass('class-name-a class-name-b');
    
17.03.2014 / 21:37