Detect if 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 certain CSS class. How can I achieve the same with pure JavaScript?

Answer:

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

div.classList.contains("foo");

Demo 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 it is also possible to 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 in JSFiddle

Scroll to Top