Detect whether an element contains a class with pure JavaScript

Question:

In jQuery we have the code

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

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

Answer:

In modern browsers it is possible to use the classList native property, so the syntax will be:

div.classList.contains("foo");

Demo on 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);
}

Demo on JSFiddle

Scroll to Top