How to Check If an Element Contains a Class in JavaScript
Read this tutorial and learn valuable information about the multiple methods that are used for checking if the element contains a class in JavaScript.
Multiple methods exist 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:
Javascript contains method check a singular element
element.classList.contains(className);But if you work with older browsers and don't want to use polyfills, use indexOf like this:
Javascript indexOf method
function hasClass(element, clsName) {
return (' ' + element.className + ' ').indexOf(' ' + clsName + ' ') > -1;
}The space padding around both strings prevents partial matches, ensuring the method returns true only for exact class names.
How to Check If an Element Contains a Class in JavaScript
<!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>