Detect if an element contains a class with pure Javascript

Asked

Viewed 20,028 times

18

In jQuery, we have the code

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

Which indicates if an element contains a certain CSS class. How can I achieve the same with pure Javascript?

  • 1

    I ask that no edits be made to add tags like jQuery, since the question is not specifically about the same and only quotes.

4 answers

20


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

div.classList.contains("foo");

Demonstration at 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);
}

Demonstration at Jsfiddle

8

6

I believe this is the most compatible way 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 of use:

element.hasClass('class-name');

Example with more than one class:

element.hasClass('class-name-a class-name-b');

-3

You can do it in a very simple way

element.className.endsWith('class-name')

Example:

        const element = document.getElementById('id-name')
        element.onclick = function() {

        if (element.className.endsWith('class-name')){
            console.log('OMG! CANT BELIEVE ITS WORKING')
        }
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.