by Sai gowtham

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

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course