How to check if an element has a class in JavaScript
In this tutorial, we will learn how to check if an HTML element has a particular class or not using JavaScript.
classList.contains() method
We can use the classList.contains() method to check if an element has a class name or not.
The classList.contains()
method returns true
if a class name is found else it returns false
(if a class name is not found).
Example:
<div class="box" id="first"> <h1>Hello happy people</h1>
</div>
const div = document.getElementById('first');
div.classList.contains('box'); // true
div.classList.contains('orange'); // false