How do I check if an element has a specific class in JavaScript?
Gable E
gable e profile pic

To check if an element has a specific class in JavaScript, you can use theclassList property and its methods. Here's a step-by-step approach: 1. Select the element: - Use a method such asgetElementById,querySelector, orquerySelectorAll to select the desired element(s). 2. Access theclassList property: - Once you have the element, access itsclassList property. This property contains a collection of the classes assigned to the element. 3. Use thecontains() method: - TheclassList object has acontains() method that allows you to check if a specific class is present on the element. - Pass the class name as an argument to thecontains() method to determine if the element has that class. Here's an example to illustrate the process:


// Select the element
const element = document.getElementById('myElement');

// Check if the element has the 'highlight' class
if (element.classList.contains('highlight')) {
  // The element has the 'highlight' class
  console.log('The element has the class "highlight"');
} else {
  // The element does not have the 'highlight' class
  console.log('The element does not have the class "highlight"');

In the example above, we select an element with the IDmyElement and use theclassList.contains() method to check if it has the class namehighlight. If the class is present, the corresponding message is logged to the console. Using theclassList property and itscontains() method allows you to easily check if an element has a specific class in JavaScript. This approach is flexible and doesn't require manually parsing or manipulating class strings.