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?
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?
In modern browsers you can use the classList native property, so syntax will be:
div.classList.contains("foo");
This "new" classList property (English) is supported from the following versions:
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);
}
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
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');