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?
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?
20
In modern browsers it is possible to use the native property classList, thus the syntax will be:
div.classList.contains("foo");
This "new" classList property (English) is supported from the following versions:
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);
}
8
Your element has the property className
which contains all classes linked 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 of use: Jsfiddle
Translated from the original issue in SOEN, after I solve my doubt there
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')
}
}
It does not work. The author of the question wants to know if an element contains a certain CSS class and not the string returned by Element classname. ends with a certain Sting. ref->String.prototype.endsWith()
Browser other questions tagged javascript
You are not signed in. Login or sign up in order to post.
I ask that no edits be made to add tags like
jQuery
, since the question is not specifically about the same and only quotes.– Tiago César Oliveira