How can I check in JavaScript if a DOM element contains a class?
I tried the following code, but for some reason it doesn\'t work...
if (document.get
hasClass:
function hasClass(element, className) {
return (element.className).indexOf(className) > -1;
}
containsClass:
function containsClass(element, className) {
return Array.from(element.classList).filter(function (cls) {
return cls.indexOf(className) > -1;
}).length > 0;
}
codepen demo
All modern browsers support the contains
method of Element.classList :
testElement.classList.contains(className)
var testElement = document.getElementById('test');
document.body.innerHTML = '<pre>' + JSON.stringify({
'main' : testElement.classList.contains('main'),
'cont' : testElement.classList.contains('cont'),
'content' : testElement.classList.contains('content'),
'main-cont' : testElement.classList.contains('main-cont'),
'main-content' : testElement.classList.contains('main-content')
}, null, 2) + '</pre>';
<div id="test" class="main main-content content"></div>
(from CanIUse.com)
If you want to use Element.classList and you also want to support ancient browsers like IE8, consider using this polyfill by Eli Grey.