How to Check If an Element Contains a Class in JavaScript
Multiple methods exists that are used to check whether the element contains a class. Let’s discuss them separately.
The first method that can handle the task is the element.classList.contains method. The function takes only one parameter. The contains method checks if your classList contains a singular element:
element.classList.contains(class);
But if you work with older browsers and don't want to use polyfills, use indexOf like this:
function hasClass(element, clsName) {
return (' ' + element.className + ' ').indexOf(' ' + clsName + ' ') > -1;
}
Otherwise, it will return true if the class you are looking for is part of another class name.
<!DOCTYPE HTML>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<div id="test" class="myClass">Welcome to W3Docs</div>
<script>
function hasClass(element, clsName) {
return(' ' + element.className + ' ').indexOf(' ' + clsName + ' ') > -1;
}
let val1 = document.getElementById('test');
alert(hasClass(val1, 'myClass'));
</script>
</body>
</html>
The hasClass() Method
The hasClass() method checks whether any of the selected elements have a specified class name. The method returns true if any of the selected elements has the specified class name. Elements may have multiple classes assigned to them.